Search Results

Search found 1474 results on 59 pages for 'datatype'.

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

  • XSLT Similar functionality to SQL "WHERE LIKE"

    - by Fishcake
    I have the following XML <Answer> <Label>FCVCMileage</Label> <Value>3258</Value> <Iteration>0</Iteration> <DataType>NUMBER</DataType> </Answer> And need to get the Value underneath the Mileage label. However the 4 letter prefix to Mileage could be any 1 of 8 different prefixes. I know I could find the value by testing for every combination using xsl:if or xsl:choose but is there a more elegant way that would work similar to the following SQL and also wouldn't need changes to code being made if other prefixes were added. WHERE label LIKE '%Mileage' NB. There will only ever be 1 label element containing the word Mileage Cheers!

    Read the article

  • Sending string to wcf service using jquery ajax. why can i only send strings of numbers?

    - by Robodude
    Hi Guys, For some reason, I'm only able to pass strings containing numbers to my web service when using jquery ajax. This hasn't been an issue so far because I was always just passing IDs to my wcf service. But I'm trying to do something more complex now but I can't figure it out. In my interface: [OperationContract] [WebInvoke(ResponseFormat = WebMessageFormat.Json)] DataTableOutput GetDataTableOutput(string json); My webservice: public DataTableOutput GetDataTableOutput(string json) { DataTableOutput x = new DataTableOutput(); x.iTotalDisplayRecords = 9; x.iTotalRecords = 50; x.sColumns = "1"; x.sEcho = "1"; x.aaData = null; return x; } Javascript/Jquery: var x = "1"; $.ajax({ type: "POST", async: false, url: "Services/Service1.svc/GetDataTableOutput", contentType: "application/json; charset=utf-8", data: x, dataType: "json", success: function (msg) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { //alert(XMLHttpRequest.status); //alert(XMLHttpRequest.responseText); } }); The above code WORKS perfectly. But when I change x to "t" or even to "{'test':'test'}" I get a Error 400 Bad Request error in Firebug. Thanks, John EDIT: Making some progress! data: JSON.stringify("{'test':'test'}"), Sends the string to my function! EDIT2: var jsonAOData = JSON.stringify(aoData); $.ajax({ type: "POST", async: false, url: sSource, contentType: "application/json; charset=utf-8", data: "{'Input':" + jsonAOData + "}", dataType: "json", success: function (msg) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { //alert(XMLHttpRequest.status); //alert(XMLHttpRequest.responseText); } }); EDIT3: I modified the code block I put in EDIT2 up above. Swapping the " and ' did the trick! $.ajax({ type: "POST", async: false, url: sSource, contentType: "application/json; charset=utf-8", data: '{"Input":' + jsonAOData + '}', dataType: "json", success: function (msg) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { //alert(XMLHttpRequest.status); //alert(XMLHttpRequest.responseText); } }); However, I have a new problem: public DataTableOutput GetDataTableOutput(DataTableInputOverview Input) { The input here is completely null. The values I passed from jsonAOData didn't get assigned to the DataTableInputOverview Input variable. :(

    Read the article

  • how to write xsd for the following xml?

    - by Venkats
    <?xml version="1.0"?> <datatype xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="sampletype.xsd"> <table name="emp"> <columns> <column> <name>emp_id</name> <data_type>int(200) </data_type> </column> </columns> </table> </datatype> Here i generate the xsd for above xml, but it was not correct. can you help me generate the xsd for the xml? thanks in advance.

    Read the article

  • F#: Can't hide a type abbreviation in a signature? Why not?

    - by Nels Beckman
    In F#, I'd like to have what I see as a fairly standard Abstract Datatype: // in ADT.fsi module ADT type my_Type // in ADT.fs module ADT type my_Type = int In other words, code inside the module knows that my_Type is an int, but code outside does not. However, F# seems to have a restriction where type abbreviations specifically cannot be hidden by a signature. This code gives a compiler error, and the restriction is described here. If my_Type were instead a discriminated union, then there is no compiler error. My question is, why the restriction? I seem to remember being able to do this in SML and Ocaml, and furthermore, isn't this a pretty standard thing to do when creating an abstract datatype? Thanks

    Read the article

  • SSIS Script Component + Helper Assemblies (.dll's)

    - by Nev_Rahd
    I got a script component which does Transformation / DataType conversions / Creating some calculated columns. All the transform validations / datatype conversion methods and for new column generation is put into custom .dll. As this script component would be same for all other tables, only thing is to define input / ouput columns and apply validation methods on required columns. This all works fine. On production server where do I need to deploy my .dll. Would just putting it into GAC will be enough or need to do something else. Regards

    Read the article

  • comparing two tables

    - by sza
    I have two identical table ie all the columns are identical and one of the datatype is Text, one is varchar(255) and the rest are int. Lets say the table name is 'AAAAA'. Table AAAAA was processed and backed up earlier this month. Both the tables were storing data and now the second table is only storing data. I need to find unmatching records from the second table (BBBBB) which is storing data right now and add those records to Table AAAAA. Your help will be highly appreciated. I tried to use 'EXCEPT' but it does not support text datatype. I'm using SQL Server 2005.

    Read the article

  • Stairway to XML: Level 2 - The XML Data Type

    Robert Sheldon describes SQL Server's XML Data Type, and shows that it is as easy to configure a variable, column, or parameter with the XML data type as configuring one of these objects with any other datatype Keep your database and application development in syncSQL Connect is a Visual Studio add-in that brings your databases into your solution. It then makes it easy to keep your database in sync, and commit to your existing source control system. Find out more.

    Read the article

  • How to handle lookup data in a C# ASP.Net MVC4 application?

    - by Jim
    I am writing an MVC4 application to track documents we have on file for our clients. I'm using code first, and have created models for my objects (Company, Document, etc...). I am now faced with the topic of document expiration. Business logic dictates certain documents will expire a set number of days past the document date. For example, Document A might expire in 180 days, Document 2 in 365 days, etc... I have a class for my documents as shown below (simplified for this example). What is the best way for me to create a lookup for expiration values? I want to specify documents of type DocumentA expire in 30 days, type DocumentB expire in 75 days, etc... I can think of a few ways to do this: Lookup table in the database I can query New property in my class (DaysValidFor) which has a custom getter that returns different values based on the DocumentType A method that takes in the document type and returns the number of days and I'm sure there are other ways I'm not even thinking of. My main concern is a) not violating any best practices and b) maintainability. Are there any pros/cons I need to be aware of for the above options, or is this a case of "just pick one and run with it"? One last thought, right now the number of days is a value that does not need to be stored anywhere on a per-document basis -- however, it is possible that business logic will change this (i.e., DocumentA's are 30 days expiration by default, but this DocumentA associated with Company XYZ will be 60 days because we like them). In that case, is a property in the Document class the best way to go, seeing as I need to add that field to the DB? namespace Models { // Types of documents to track public enum DocumentType { DocumentA, DocumentB, DocumentC // etc... } // Document model public class Document { public int DocumentID { get; set; } // Foreign key to companies public int CompanyID { get; set; } public DocumentType DocumentType { get; set; } // Helper to translate enum's value to an integer for DB storage [Column("DocumentType")] public int DocumentTypeInt { get { return (int)this.DocumentType; } set { this.DocumentType = (DocumentType)value; } } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)] public DateTime DocumentDate { get; set; } // Navigation properties public virtual Company Company { get; set; } } }

    Read the article

  • Find Column in All Databases

    - by Derek Dieter
    Occasionally, there comes a requirement to search all databases on a particular server for either columns with a specific name, or columns relating to a specific subject. In the most recent case, I had to find all similar columns in all databases because the company plans to change the datatype of these columns. [...]

    Read the article

  • SQL Date Comparison

    - by Derek Dieter
    When comparing the datetime datatype in SQL Server, it is important to maintain consistency in order to gaurd against SQL interpreting a date differently than you intend. In at least one occasion I have seen someone specify a short format for a date, like (1/4/08) only to find that SQL interpreted the month as [...]

    Read the article

  • Dojo - How to position tooltip close to text?

    - by user244394
    Like the title says i want to be able to display the tooltip close to the text, currently it is displayed far away in the cell. Tobe noted the tooltip positions correctly for large text, only fails for small text. In DOJO How can i position the tooltip close to the text? I have this bit of code snippet that display the tooltip in the grid cells. Screenshot attached, html <div class="some_app claro"></div> ... com.c.widget.EnhancedGrid = function ( aParent, options ) { var grid, options; this.theParentApp = aParent; dojo.require("dojox.grid.EnhancedGrid"); dojo.require("dojox.grid.enhanced.plugins.Menu"); dojo.require("dojox.grid.enhanced.plugins.Selector"); dojo.require("dojox.grid.enhanced.plugins.Pagination"); dojo.require("dojo.store.Memory"); dojo.require("dojo.data.ObjectStore"); dojo.require("dojo._base.xhr"); dojo.require("dojo.domReady!"); dojo.require("dojo.date.locale"); dojo.require("dojo._base.connect"); dojo.require("dojox.data.JsonRestStore"); dojo.require("dojo.data.ItemFileReadStore"); dojo.require("dijit.Menu"); dojo.require("dijit.MenuItem"); dojo.require('dijit.MenuSeparator'); dojo.require('dijit.CheckedMenuItem'); dojo.require('dijit.Tooltip'); dojo.require('dojo/query'); dojo.require("dojox.data.QueryReadStore"); // main initialization function this.init = function( options ) { var me = this; // default options var defaultOptions = { widgetName: ' Enhancedgrid', render: true, // immediately render the grid draggable: true, // disables column dragging containerNode: false, // the Node to hold the Grid (optional) mashupUrl: false, // the URL of the mashup (required) rowsPerPage: 20, //Default number of items per page columns: false, // columns (required) width: "100%", // width of grid height: "100%", // height of grid rowClass: function (rowData) {}, onClick: function () {}, headerMenu: false, // adding a menu pop-up for the header. selectedRegionMenu: false, // adding a menu pop-up for the rows. menusObject: false, //object to start-up the menus using the plug-in. sortInfo: false, // The column default sort infiniteScrolling: false //If true, the enhanced grid will have an infinite scrolling. }; // merge user provided options me.options = jQuery.extend( {}, defaultOptions, options ); // check we have minimum required options if ( ! me.options.mashupUrl ){ throw ("You must supply a mashupUrl"); } if ( ! me.options.columns ){ throw ("You must supply columns"); } // make the column for formatting based on its data type. me.preProcessColumns(); // create the Contextual Menu me.createMenu(); // create the grid object and return me.createGrid(); }; // Loading the data to the grid. this.loadData = function () { var me = this; if (!me.options.infiniteScrolling) { var xhrArgs = { url: me.options.mashupUrl, handleAs: "json", load: function( data ){ var store = new dojo.data.ItemFileReadStore({ data : {items : eval( "data."+me.options.dataRoot)}}); store.fetch({ onComplete : function(items, request) { if (me.grid.selection !== null) { me.grid.selection.clear(); } me.grid.setStore(store); }, onError : function(error) { me.onError(error); } }); }, error: function (error) { me.onError(error); } }; dojo.xhrGet(xhrArgs); } else { dojo.declare('NotificationQueryReadStore', dojox.data.QueryReadStore, { // // hacked -- override to map to proper data structure // from mashup // _xhrFetchHandler : function(data, request, fetchHandler, errorHandler) { // // TODO: need to have error handling here when // data has "error" data structure // // // remap data object before process by super method // var dataRoot = eval ("data."+me.options.dataRoot); var dataTotal = eval ("data."+me.options.dataTotal); data = { numRows : dataTotal, items : dataRoot }; // call to super method to process mapped data and // set rowcount // for proper display this.inherited(arguments); } }); var queryStore = new NotificationQueryReadStore({ url : me.options.mashupUrl, urlPreventCache: true, requestMethod : "get", onError: function (error) { me.onError(error); } }); me.grid.setStore(queryStore); } }; this.preProcessColumns = function () { var me = this; var options = me.options; for (i=0;i<this.options.columns.length;i++) { if (this.options.columns[i].formatter==null) { switch (this.options.columns[i].datatype) { case "string": this.options.columns[i].formatter = me.formatString; break; case "date": this.options.columns[i].formatter = me.formatDate; var todayDate = new Date(); var gmtTime = c.util.Date.parseDate(todayDate.toString()).toString(); var gmtval = gmtTime.substring(gmtTime.indexOf('GMT'),(gmtTime.indexOf('(')-1)); this.options.columns[i].name = this.options.columns[i].name + " ("+gmtval+")"; } } if (this.options.columns[i].sortDefault) { me.options.sortInfo = i+1; } } }; // create GRID object using supplied options this.createGrid = function () { var me = this; var options = me.options; // create a new grid this.grid = new dojox.grid.EnhancedGrid ({ width: options.width, height: options.height, query: { id: "*" }, keepSelection: true, formatterScope: this, structure: options.columns, columnReordering: options.draggable, rowsPerPage: options.rowsPerPage, //sortInfo: options.sortInfo, plugins : { menus: options.menusObject, selector: {"row":"multi", "cell": "disabled" }, }, //Allow the user to decide if a column is sortable by setting sortable = true / false canSort: function(col) { if (options.columns[Math.abs(col)-1].sortable) return true; else return false; }, //Change the row colors depending on severity column. onStyleRow: function (row) { var grid = me.grid; var item = grid.getItem(row.index); if (item && options.rowClass(item)) { row.customClasses += " " +options.rowClass(item); if (grid.selection.selectedIndex == row.index) { row.customClasses += " dojoxGridRowSelected"; } grid.focus.styleRow(row); grid.edit.styleRow(row); } }, onCellMouseOver: function (e){ // var pos = dojo.position(this, true); // alert(pos); console.log( e.rowIndex +" cell node :"+ e.cellNode.innerHTML); // var pos = dojo.position(this, true); console.log( " pos :"+ e.pos); if (e.cellNode.innerHTML!="") { dijit.showTooltip(e.cellNode.innerHTML, e.cellNode); } }, onCellMouseOut: function (e){ dijit.hideTooltip(e.cellNode); }, onHeaderCellMouseOver: function (e){ if (e.cellNode.innerHTML!="") { dijit.showTooltip(e.cellNode.innerHTML, e.cellNode); } }, onHeaderCellMouseOut: function (e){ dijit.hideTooltip(e.cellNode); }, }); // ADDED CODE FOR TOOLTIP var gridTooltip = new Tooltip({ connectId: "grid1", selector: "td", position: ["above"], getContent: function(matchedNode){ var childNode = matchedNode.childNodes[0]; if(childNode.nodeType == 1 && childNode.className == "user") { this.position = ["after"]; this.open(childNode); return false; } if(matchedNode.className && matchedNode.className == "user") { this.position = ["after"]; } else { this.position = ["above"]; } return matchedNode.textContent; } }); ... //Construct the grid this.buildGrid = function(){ var datagrid = new com.emc.widget.EnhancedGrid(this,{ Url: "/dge/api/-resultFormat=json&id="+encodeURIComponent(idUrl), dataRoot: "Root.ATrail", height: '100%', columns: [ { name: 'Time', field: 'Time', width: '20%', datatype: 'date', sortable: true, searchable: true, hidden: false}, { name: 'Type', field: 'Type', width: '20%', datatype: 'string', sortable: true, searchable: true, hidden: false}, { name: 'User ID', field: 'UserID', width: '20%', datatype: 'string', sortable: true, searchable: true, hidden: false } ] }); this.grid = datagrid; };

    Read the article

  • Creating a Dynamic DataRow for easier DataRow Syntax

    - by Rick Strahl
    I've been thrown back into an older project that uses DataSets and DataRows as their entity storage model. I have several applications internally that I still maintain that run just fine (and I sometimes wonder if this wasn't easier than all this ORM crap we deal with with 'newer' improved technology today - but I disgress) but use this older code. For the most part DataSets/DataTables/DataRows are abstracted away in a pseudo entity model, but in some situations like queries DataTables and DataRows are still surfaced to the business layer. Here's an example. Here's a business object method that runs dynamic query and the code ends up looping over the result set using the ugly DataRow Array syntax:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { string title = row["title"] as string; string safeTitle = row["safeTitle"] as string; int pk = (int)row["pk"]; string newSafeTitle = this.GetSafeTitle(title); if (newSafeTitle != safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",pk) ); result++; } } return result; } The problem with looping over DataRow objecs is two fold: The array syntax is tedious to type and not real clear to look at, and explicit casting is required in order to do anything useful with the values. I've highlighted the place where this matters. Using the DynamicDataRow class I'll show in a minute this code can be changed to look like this:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { dynamic entry = new DynamicDataRow(row); string newSafeTitle = this.GetSafeTitle(entry.title); if (newSafeTitle != entry.safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",entry.pk) ); result++; } } return result; } The code looks much a bit more natural and describes what's happening a little nicer as well. Well, using the new dynamic features in .NET it's actually quite easy to implement the DynamicDataRow class. Creating your own custom Dynamic Objects .NET 4.0 introduced the Dynamic Language Runtime (DLR) and opened up a whole bunch of new capabilities for .NET applications. The dynamic type is an easy way to avoid Reflection and directly access members of 'dynamic' or 'late bound' objects at runtime. There's a lot of very subtle but extremely useful stuff that dynamic does (especially for COM Interop scenearios) but in its simplest form it often allows you to do away with manual Reflection at runtime. In addition you can create DynamicObject implementations that can perform  custom interception of member accesses and so allow you to provide more natural access to more complex or awkward data structures like the DataRow that I use as an example here. Bascially you can subclass DynamicObject and then implement a few methods (TryGetMember, TrySetMember, TryInvokeMember) to provide the ability to return dynamic results from just about any data structure using simple property/method access. In the code above, I created a custom DynamicDataRow class which inherits from DynamicObject and implements only TryGetMember and TrySetMember. Here's what simple class looks like:/// <summary> /// This class provides an easy way to turn a DataRow /// into a Dynamic object that supports direct property /// access to the DataRow fields. /// /// The class also automatically fixes up DbNull values /// (null into .NET and DbNUll to DataRow) /// </summary> public class DynamicDataRow : DynamicObject { /// <summary> /// Instance of object passed in /// </summary> DataRow DataRow; /// <summary> /// Pass in a DataRow to work off /// </summary> /// <param name="instance"></param> public DynamicDataRow(DataRow dataRow) { DataRow = dataRow; } /// <summary> /// Returns a value from a DataRow items array. /// If the field doesn't exist null is returned. /// DbNull values are turned into .NET nulls. /// /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; try { result = DataRow[binder.Name]; if (result == DBNull.Value) result = null; return true; } catch { } result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { try { if (value == null) value = DBNull.Value; DataRow[binder.Name] = value; return true; } catch {} return false; } } To demonstrate the basic features here's a short test: [TestMethod] [ExpectedException(typeof(RuntimeBinderException))] public void BasicDataRowTests() { DataTable table = new DataTable("table"); table.Columns.Add( new DataColumn() { ColumnName = "Name", DataType=typeof(string) }); table.Columns.Add( new DataColumn() { ColumnName = "Entered", DataType=typeof(DateTime) }); table.Columns.Add(new DataColumn() { ColumnName = "NullValue", DataType = typeof(string) }); DataRow row = table.NewRow(); DateTime now = DateTime.Now; row["Name"] = "Rick"; row["Entered"] = now; row["NullValue"] = null; // converted in DbNull dynamic drow = new DynamicDataRow(row); string name = drow.Name; DateTime entered = drow.Entered; string nulled = drow.NullValue; Assert.AreEqual(name, "Rick"); Assert.AreEqual(entered,now); Assert.IsNull(nulled); // this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); } The DynamicDataRow requires a custom constructor that accepts a single parameter that sets the DataRow. Once that's done you can access property values that match the field names. Note that types are automatically converted - no type casting is needed in the code you write. The class also automatically converts DbNulls to regular nulls and vice versa which is something that makes it much easier to deal with data returned from a database. What's cool here isn't so much the functionality - even if I'd prefer to leave DataRow behind ASAP -  but the fact that we can create a dynamic type that uses a DataRow as it's 'DataSource' to serve member values. It's pretty useful feature if you think about it, especially given how little code it takes to implement. By implementing these two simple methods we get to provide two features I was complaining about at the beginning that are missing from the DataRow: Direct Property Syntax Automatic Type Casting so no explicit casts are required Caveats As cool and easy as this functionality is, it's important to understand that it doesn't come for free. The dynamic features in .NET are - well - dynamic. Which means they are essentially evaluated at runtime (late bound). Rather than static typing where everything is compiled and linked by the compiler/linker, member invokations are looked up at runtime and essentially call into your custom code. There's some overhead in this. Direct invocations - the original code I showed - is going to be faster than the equivalent dynamic code. However, in the above code the difference of running the dynamic code and the original data access code was very minor. The loop running over 1500 result records took on average 13ms with the original code and 14ms with the dynamic code. Not exactly a serious performance bottleneck. One thing to remember is that Microsoft optimized the DLR code significantly so that repeated calls to the same operations are routed very efficiently which actually makes for very fast evaluation. The bottom line for performance with dynamic code is: Make sure you test and profile your code if you think that there might be a performance issue. However, in my experience with dynamic types so far performance is pretty good for repeated operations (ie. in loops). While usually a little slower the perf hit is a lot less typically than equivalent Reflection work. Although the code in the second example looks like standard object syntax, dynamic is not static code. It's evaluated at runtime and so there's no type recognition until runtime. This means no Intellisense at development time, and any invalid references that call into 'properties' (ie. fields in the DataRow) that don't exist still cause runtime errors. So in the case of the data row you still get a runtime error if you mistype a column name:// this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); Dynamic - Lots of uses The arrival of Dynamic types in .NET has been met with mixed emotions. Die hard .NET developers decry dynamic types as an abomination to the language. After all what dynamic accomplishes goes against all that a static language is supposed to provide. On the other hand there are clearly scenarios when dynamic can make life much easier (COM Interop being one place). Think of the possibilities. What other data structures would you like to expose to a simple property interface rather than some sort of collection or dictionary? And beyond what I showed here you can also implement 'Method missing' behavior on objects with InvokeMember which essentially allows you to create dynamic methods. It's all very flexible and maybe just as important: It's easy to do. There's a lot of power hidden in this seemingly simple interface. Your move…© Rick Strahl, West Wind Technologies, 2005-2011Posted in CSharp  .NET   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • JqGrid addJSONData + ASP.NET 2.0 WS

    - by MilosC
    Dear community ! I am a bit lost. I' ve tried to implement a solution based on JqGrid and tried to use function as datatype. I've setted all by the book i guess, i get WS invoked and get JASON back, I got succes on clientside in ajaf call and i "bind" jqGrid using addJSONData but grid remains empty. I do not have any glue now... other "local" samples on same pages works without a problem (jsonstring ...) My WS method looks like : [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetGridData() { // Load a list InitSessionVariables(); SA.DB.DenarnaEnota.DenarnaEnotaDB db = new SAOP.SA.DB.DenarnaEnota.DenarnaEnotaDB(); DataSet ds = db.GetLookupForDenarnaEnota(SAOP.FW.DB.RecordStatus.All); // Turn into HTML friendly format GetGridData summaryList = new GetGridData(); summaryList.page = "1"; summaryList.total = "10"; summaryList.records = "160"; int i = 0; foreach (DataRow dr in ds.Tables[0].Rows) { GridRows row = new GridRows(); row.id = dr["DenarnaEnotaID"].ToString(); row.cell = "[" + "\"" + dr["DenarnaEnotaID"].ToString() + "\"" + "," + "\"" + dr["Kratica"].ToString() + "\"" + "," + "\"" + dr["Naziv"].ToString() + "\"" + "," + "\"" + dr["Sifra"].ToString() + "\"" + "]"; summaryList.rows.Add(row); } return JsonConvert.SerializeObject(summaryList); } my ASCX code is this: jQuery(document).ready(function(){ jQuery("#list").jqGrid({ datatype : function (postdata) { jQuery.ajax({ url:'../../AjaxWS/TemeljnicaEdit.asmx/GetGridData', data:'{}', dataType:'json', type: 'POST', contentType: "application/json; charset=utf-8", complete: function(jsondata,stat){ if(stat=="success") { var clearJson = jsondata.responseText; var thegrid = jQuery("#list")[0]; var myjsongrid = eval('('+clearJson+')'); alfs thegrid.addJSONData(myjsongrid.replace(/\\/g,'')); } } } ); }, colNames:['DenarnaEnotaID','Kratica', 'Sifra', 'Naziv'], colModel:[ {name:'DenarnaEnotaID',index:'DenarnaEnotaID', width:100}, {name:'Kratica',index:'Kratica', width:100}, {name:'Sifra',index:'Sifra', width:100}, {name:'Naziv',index:'Naziv', width:100}], rowNum:15, rowList:[15,30,100], pager: jQuery('#pager'), sortname: 'id', // loadtext:"Nalagam zapise...", // viewrecords: true, sortorder: "desc", // caption:"Vrstice", // width:"800", imgpath: "../Scripts/JGrid/themes/basic/images"}); }); from WS i GET JSON like this: {”page”:”1?,”total”:”10?,”records”:”160?,”rows”:[{"id":"18","cell":"["18","BAM","Konvertibilna marka","977"]“},{”id”:”19?,”cell”:”["19","RSD","Srbski dinar","941"]“},{”id”:”20?,”cell”:”["20","AFN","Afgani","971"]“},{”id”:”21?,”cell”:”["21","ALL","Lek","008"]“},{”id”:”22?,”cell”:”["22","DZD","Alžirski dinar","012"]“},{”id”:”23?,”cell”:”["23","AOA","Kvanza","973"]“},{”id”:”24?,”cell”:”["24","XCD","Vzhodnokaribski dolar","951"]“},{”id”:”25?,”cell”:” ……………… ["13","PLN","Poljski zlot","985"]“},{”id”:”14?,”cell”:”["14","SEK","Švedska krona","752"]“},{”id”:”15?,”cell”:”["15","SKK","Slovaška krona","703"]“},{”id”:”16?,”cell”:”["16","USD","Ameriški dolar","840"]“},{”id”:”17?,”cell”:”["17","XXX","Nobena valuta","000"]“},{”id”:”1?,”cell”:”["1","SIT","Slovenski tolar","705"]“}]} i have registered this js : clientSideScripts.RegisterClientScriptFile("prototype.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/prototype-1.6.0.2.js")); clientSideScripts.RegisterClientScriptFile("jquery.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.js")); clientSideScripts.RegisterClientScriptFile("jquery.jqGrid.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.jqGrid.js")); clientSideScripts.RegisterClientScriptFile("jqModal.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqModal.js")); clientSideScripts.RegisterClientScriptFile("jqDnR.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqDnR.js")); Basical i think it must be something stupid ...but i can figure it out now... Help wanted.

    Read the article

  • How can I bind the nested viewmodels to properties of a control

    - by Robert
    I used Microsoft's Chart Control of the WPF toolkit to write my own chart control. I blogged about it here. My Chart control stacks the yaxes in the chart on top of each other. As you can read in the article this all works quite well. Now I want to create a viewmodel that controls the data and axes in the chart. So far I'm able to add axes to the chart and show them in the chart. But I have a problem when I try to add the lineseries because it has one DependentAxis and one InDependentAxis property. I don't know how to assign the proper xAxis and yAxis controls to it. Below you see part of the LineSeriesViewModel. It has a nested XAxisViewModel and YAxisViewModel property. public class LineSeriesViewModel : ViewModelBase, IChartComponent { XAxisViewModel _xAxis; public XAxisViewModel XAxis { get { return _xAxis; } set { _xAxis = value; RaisePropertyChanged(() => XAxis); } } //The YAxis Property look the same } The viewmodels all have their own datatemplate. The xaml code looks like this: <UserControl.Resources> <DataTemplate x:Key="xAxisTemplate" DataType="{x:Type l:YAxisViewModel}"> <chart:LinearAxis x:Name="yAxis" Orientation="Y" Location="Left" Minimum="0" Maximum="10" IsHitTestVisible="False" Width="50" /> </DataTemplate> <DataTemplate x:Key="yAxisTemplate" DataType="{x:Type l:XAxisViewModel}"> <chart:LinearAxis x:Name="xAxis" Orientation="X" Location="Bottom" Minimum="0" Maximum="100" IsHitTestVisible="False" Height="50" /> </DataTemplate> <DataTemplate DataType="{x:Type l:LineSeriesViewModel}"> <!--Binding doesn't work on the Dependent and IndependentAxis! --> <!--YAxis XAxis and Series are properties of the LineSeriesViewModel --> <l:FastLineSeries DependentAxis="{Binding Path=YAxis}" IndependentAxis="{Binding Path=XAxis}" ItemsSource="{Binding Path=Series}"/> </DataTemplate> <Style TargetType="ItemsControl"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <!--My stacked chart control --> <l:StackedPanel x:Name="stackedPanel" Width="Auto" Height="Auto" Background="LightBlue"> </l:StackedPanel> </ItemsPanelTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ClipToBounds="True"> <!-- View is an ObservableCollection of all axes and series--> <ItemsControl x:Name="chartItems" ItemsSource="{Binding Path=View}" Focusable="False"> </ItemsControl> </Grid> This code works quite well. When I add axes they get drawn. But the DependentAxis and InDependentAxis of the lineseries control stay null, so the series doesn't get drawn. How can I bind the nested viewmodels to the properties of a control?

    Read the article

  • WPF Tree doesn't work

    - by phenevo
    Could you tell me why I can't see subItems? I've got winforms apps and I added my wpfusercontrol:ObjectsAndZonesTree ServiceProvider is my webservice. Adn method to get listofcountires with subitems works properly (i get countires, regions from this countires, provinces etc...) ElementHost elementHost = new ElementHost { Width = 150, Height = 50, Dock = DockStyle.Fill, Child = new ObjectsAndZonesTree() }; this.splitContainer3.Panel1.Controls.Add(elementHost); XAML: <TreeView Name="GroupView" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type ServiceProvider:Country }" ItemsSource="{Binding Items}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type ServiceProvider:Region}" > <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> <DataTemplate DataType="{x:Type ServiceProvider:Province}" > <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> </TreeView.Resources> </TreeView> XAML.CS public ObjectsAndZonesTree() { InitializeComponent(); LoadView(); } private void LoadView() { GroupView.ItemsSource = new ServiceProvider().GetListOfObjectsAndZones(); } class Country: public class Country { string _name; [XmlAttribute] public string Name { get { return _name; } set { _name = value; } } string _code; [XmlAttribute] public string Code { get { return _code; } set { _code = value; } } string _continentCode; [XmlAttribute] public string ContinentCode { get { return _continentCode; } set { _continentCode = value; } } public Region[] ListOfRegions { get { return _listOfRegions; } set { _listOfRegions = value; } } private Region[] _listOfRegions; public IList<object> Items { get { IList<object> childNodes = new List<object>(); foreach (var group in this.ListOfRegions) childNodes.Add(group); return childNodes; } } } Class Region: public class Region { private Province[] _listOfProvinces; private string _name; private string _code; public Province[] ListOfProvinces { get { return _listOfProvinces; } set { _listOfProvinces = value; } } public string Name { get { return _name; } set { _name = value; } } public string Code { get { return _code; } set { _code = value; } } public string CountryCode { get { return _countryCode; } set { _countryCode = value; } } private string _countryCode; public IList<object> Items { get { IList<object> childNodes = new List<object>(); foreach (var group in this.ListOfProvinces) childNodes.Add(group); return childNodes; } } } It displays me only list of countires.

    Read the article

  • How to bind Data to Dropdownlist in Kendo Ui Mobile

    - by dinesh Haraveer
    I have been using Kendo Mobile to develop an application, previously same application i have done in Kendo web,it's works fine.The main problem is that i have to bind data to two dropdownlist which the below code i have written,when my application is running it show an error like "Microsoft JScript runtime error: Object doesn't support property or method 'append'". in HTML <div id="forms" data-role="view" data-title="Form Elements" data-init="initForm"> <table> <tr> <td> <label style="margin-left: 20px"> Company:</label> </td> <td> <select id="ddlCompany" style="width: 200px"> <option>Select Company</option> </select> </td> <td class="style1"> <label style="margin-left: 20px"> Category:</label> </td> <td> <select id="ddlCategory" style="width: 200px"> <option>Select Category</option> </select> </td> <td> <label style="margin-left: 20px"> Product :</label> </td> <td> <select id="ddlProduct" style="width: 200px"> <option>Select Product</option> </select> </td> </tr> </table> </div> function initForm() { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "FlashReportMobileWebService.asmx/GetCompany", dataType: "json", success: function (data) { for (i = 0; i < data.d.length; i++) { ddlCompany.append($("<option></option>").val(data.d[i].Company).html(data.d[i].Company)); }; $("#ddlCompany").kendoDropDownList(); } }); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "FlashReportMobileWebService.asmx/ToCategoryDropDown", dataType: "json", success: function (data) { for (i = 0; i < data.d.length; i++) { ddlCategory.append($("<option></option>").val(data.d[i].Category).html(data.d[i].Category)); }; $("#ddlCategory").kendoDropDownList(); }, failure: function (msg) { alert(msg); } }); } $("#ddlCategory").change( function (e) { var ddlProduct= $("#ddlProduct"); var dataItem = $("#ddlCategory").val(); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: "{'Category':'" + dataItem + "'}", url: "FlashReportWebService.asmx/ToFillProductDropDown", dataType: "json", success: function (data) { ddlProduct.empty(); for (i = 0; i < data.d.length; i++) { ddlProduct.append($("<option></option>").val(data.d[i].ProductName).html(data.d[i].ProductName)); }; $("#ddlProduct").kendoDropDownList(); }, failure: function (msg) { alert(msg); } }); }); var app = new kendo.mobile.Application(document.body); thanks for reading this

    Read the article

  • Sending changes from multiple tables in disconnected dataset to SQLServer...

    - by Stecy
    We have a third party application that accept calls using an XML RPC mechanism for calling stored procs. We send a ZIP-compressed dataset containing multiple tables with a bunch of update/delete/insert using this mechanism. On the other end, a CLR sproc decompress the data and gets the dataset. Then, the following code gets executed: using (var conn = new SqlConnection("context connection=true")) { if (conn.State == ConnectionState.Closed) conn.Open(); try { foreach (DataTable table in ds.Tables) { string columnList = ""; for (int i = 0; i < table.Columns.Count; i++) { if (i == 0) columnList = table.Columns[0].ColumnName; else columnList += "," + table.Columns[i].ColumnName; } var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn); var builder = new SqlCommandBuilder(da); builder.ConflictOption = ConflictOption.OverwriteChanges; da.RowUpdating += onUpdatingRow; da.Update(ds, table.TableName); } } catch (....) { ..... } } Here's the event handler for the RowUpdating event: public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e) { if ((e.StatementType == StatementType.Update) && (e.Command == null)) { e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter); e.Status = UpdateStatus.Continue; } } and the CreateUpdateCommand method: private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da) { string whereClause = ""; string setClause = ""; SqlConnection conn = da.SelectCommand.Connection; for (int i = 0; i < row.Table.Columns.Count; i++) { char quoted; if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) || (row.Table.Columns[i].DataType == Type.GetType("System.DateTime"))) quoted = '\''; else quoted = ' '; string val = row[i].ToString(); if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean")) val = (bool)row[i] ? "1" : "0"; bool isPrimaryKey = false; for (int j = 0; j < row.Table.PrimaryKey.Length; j++) { if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName) { if (whereClause != "") whereClause += " AND "; if (row[i] == DBNull.Value) whereClause += row.Table.Columns[i].ColumnName + "=NULL"; else whereClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; isPrimaryKey = true; break; } } /* Only values for column that is not a primary key can be modified */ if (!isPrimaryKey) { if (setClause != "") setClause += ", "; if (row[i] == DBNull.Value) setClause += row.Table.Columns[i].ColumnName + "=NULL"; else setClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; } } return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn); } However, this is really slow when we have a lot of records. Is there a way to optimize this or an entirely different way to send lots of udpate/delete on several tables? I would really much like to use TSQL for this but can't figure a way to send a dataset to a regular sproc. Additional notes: We cannot directly access the SQLServer database. We tried without compression and it was slower.

    Read the article

  • What's New in ASP.NET 4

    - by Navaneeth
    The .NET Framework version 4 includes enhancements for ASP.NET 4 in targeted areas. Visual Studio 2010 and Microsoft Visual Web Developer Express also include enhancements and new features for improved Web development. This document provides an overview of many of the new features that are included in the upcoming release. This topic contains the following sections: ASP.NET Core Services ASP.NET Web Forms ASP.NET MVC Dynamic Data ASP.NET Chart Control Visual Web Developer Enhancements Web Application Deployment with Visual Studio 2010 Enhancements to ASP.NET Multi-Targeting ASP.NET Core Services ASP.NET 4 introduces many features that improve core ASP.NET services such as output caching and session state storage. Extensible Output Caching Since the time that ASP.NET 1.0 was released, output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch. However, this approach has a limitation — generated content always has to be stored in memory. On servers that experience heavy traffic, the memory requirements for output caching can compete with memory requirements for other parts of a Web application. ASP.NET 4 adds extensibility to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. These storage options can include local or remote disks, cloud storage, and distributed cache engines. Output-cache provider extensibility in ASP.NET 4 lets you design more aggressive and more intelligent output-caching strategies for Web sites. For example, you can create an output-cache provider that caches the "Top 10" pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers. You create a custom output-cache provider as a class that derives from the OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element For more information and for examples that show how to configure the output cache, see outputCache Element for caching (ASP.NET Settings Schema). For more information about the classes that support caching, see the documentation for the OutputCache and OutputCacheProvider classes. By default, in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache. The defaultProvider attribute for ASP.NET is AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider attribute. In addition, you can select different output-cache providers for individual control and for individual requests and programmatically specify which provider to use. For more information, see the HttpApplication.GetOutputCacheProviderName(HttpContext) method. The easiest way to choose a different output-cache provider for different Web user controls is to do so declaratively by using the new providerName attribute in a page or control directive, as shown in the following example: <%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %> Preloading Web Applications Some Web applications must load large amounts of data or must perform expensive initialization processing before serving the first request. In earlier versions of ASP.NET, for these situations you had to devise custom approaches to "wake up" an ASP.NET application and then run initialization code during the Application_Load method in the Global.asax file. To address this scenario, a new application preload manager (autostart feature) is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The preload feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests. It lets you perform expensive application initialization prior to processing the first HTTP request. For example, you can use the application preload manager to initialize an application and then signal a load-balancer that the application was initialized and ready to accept HTTP traffic. To use the application preload manager, an IIS administrator sets an application pool in IIS 7.5 to be automatically started by using the following configuration in the applicationHost.config file: <applicationPools> <add name="MyApplicationPool" startMode="AlwaysRunning" /> </applicationPools> Because a single application pool can contain multiple applications, you specify individual applications to be automatically started by using the following configuration in the applicationHost.config file: <sites> <site name="MySite" id="1"> <application path="/" serviceAutoStartEnabled="true" serviceAutoStartProvider="PrewarmMyCache" > <!-- Additional content --> </application> </site> </sites> <!-- Additional content --> <serviceAutoStartProviders> <add name="PrewarmMyCache" type="MyNamespace.CustomInitialization, MyLibrary" /> </serviceAutoStartProviders> When an IIS 7.5 server is cold-started or when an individual application pool is recycled, IIS 7.5 uses the information in the applicationHost.config file to determine which Web applications have to be automatically started. For each application that is marked for preload, IIS7.5 sends a request to ASP.NET 4 to start the application in a state during which the application temporarily does not accept HTTP requests. When it is in this state, ASP.NET instantiates the type defined by the serviceAutoStartProvider attribute (as shown in the previous example) and calls into its public entry point. You create a managed preload type that has the required entry point by implementing the IProcessHostPreloadClient interface, as shown in the following example: public class CustomInitialization : System.Web.Hosting.IProcessHostPreloadClient { public void Preload(string[] parameters) { // Perform initialization. } } After your initialization code runs in the Preload method and after the method returns, the ASP.NET application is ready to process requests. Permanently Redirecting a Page Content in Web applications is often moved over the lifetime of the application. This can lead to links to be out of date, such as the links that are returned by search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using the Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 (Found) response (which is used for a temporary redirect). This results in an extra HTTP round trip. ASP.NET 4 adds a RedirectPermanent helper method that makes it easy to issue HTTP 301 (Moved Permanently) responses, as in the following example: RedirectPermanent("/newpath/foroldcontent.aspx"); Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects. Session State Compression By default, ASP.NET provides two options for storing session state across a Web farm. The first option is a session state provider that invokes an out-of-process session state server. The second option is a session state provider that stores data in a Microsoft SQL Server database. Because both options store state information outside a Web application's worker process, session state has to be serialized before it is sent to remote storage. If a large amount of data is saved in session state, the size of the serialized data can become very large. ASP.NET 4 introduces a new compression option for both kinds of out-of-process session state providers. By using this option, applications that have spare CPU cycles on Web servers can achieve substantial reductions in the size of serialized session state data. You can set this option using the new compressionEnabled attribute of the sessionState element in the configuration file. When the compressionEnabled configuration option is set to true, ASP.NET compresses (and decompresses) serialized session state by using the .NET Framework GZipStreamclass. The following example shows how to set this attribute. <sessionState mode="SqlServer" sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate" allowCustomSqlDatabase="true" compressionEnabled="true" /> ASP.NET Web Forms Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been in this area for ASP.NET 4, such as the following: The ability to set meta tags. More control over view state. Support for recently introduced browsers and devices. Easier ways to work with browser capabilities. Support for using ASP.NET routing with Web Forms. More control over generated IDs. The ability to persist selected rows in data controls. More control over rendered HTML in the FormView and ListView controls. Filtering support for data source controls. Enhanced support for Web standards and accessibility Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties Two properties have been added to the Page class: MetaKeywords and MetaDescription. These two properties represent corresponding meta tags in the HTML rendered for a page, as shown in the following example: <head id="Head1" runat="server"> <title>Untitled Page</title> <meta name="keywords" content="keyword1, keyword2' /> <meta name="description" content="Description of my page" /> </head> These two properties work like the Title property does, and they can be set in the @ Page directive. For more information, see Page.MetaKeywords and Page.MetaDescription. Enabling View State for Individual Controls A new property has been added to the Control class: ViewStateMode. You can use this property to disable view state for all controls on a page except those for which you explicitly enable view state. View state data is included in a page's HTML and increases the amount of time it takes to send a page to the client and post it back. Storing more view state than is necessary can cause significant decrease in performance. In earlier versions of ASP.NET, you could reduce the impact of view state on a page's performance by disabling view state for specific controls. But sometimes it is easier to enable view state for a few controls that need it instead of disabling it for many that do not need it. For more information, see Control.ViewStateMode. Support for Recently Introduced Browsers and Devices ASP.NET includes a feature that is named browser capabilities that lets you determine the capabilities of the browser that a user is using. Browser capabilities are represented by the HttpBrowserCapabilities object which is stored in the HttpRequest.Browser property. Information about a particular browser's capabilities is defined by a browser definition file. In ASP.NET 4, these browser definition files have been updated to contain information about recently introduced browsers and devices such as Google Chrome, Research in Motion BlackBerry smart phones, and Apple iPhone. Existing browser definition files have also been updated. For more information, see How to: Upgrade an ASP.NET Web Application to ASP.NET 4 and ASP.NET Web Server Controls and Browser Capabilities. The browser definition files that are included with ASP.NET 4 are shown in the following list: •blackberry.browser •chrome.browser •Default.browser •firefox.browser •gateway.browser •generic.browser •ie.browser •iemobile.browser •iphone.browser •opera.browser •safari.browser A New Way to Define Browser Capabilities ASP.NET 4 includes a new feature referred to as browser capabilities providers. As the name suggests, this lets you build a provider that in turn lets you write custom code to determine browser capabilities. In ASP.NET version 3.5 Service Pack 1, you define browser capabilities in an XML file. This file resides in a machine-level folder or an application-level folder. Most developers do not need to customize these files, but for those who do, the provider approach can be easier than dealing with complex XML syntax. The provider approach makes it possible to simplify the process by implementing a common browser definition syntax, or a database that contains up-to-date browser definitions, or even a Web service for such a database. For more information about the new browser capabilities provider, see the What's New for ASP.NET 4 White Paper. Routing in ASP.NET 4 ASP.NET 4 adds built-in support for routing with Web Forms. Routing is a feature that was introduced with ASP.NET 3.5 SP1 and lets you configure an application to use URLs that are meaningful to users and to search engines because they do not have to specify physical file names. This can make your site more user-friendly and your site content more discoverable by search engines. For example, the URL for a page that displays product categories in your application might look like the following example: http://website/products.aspx?categoryid=12 By using routing, you can use the following URL to render the same information: http://website/products/software The second URL lets the user know what to expect and can result in significantly improved rankings in search engine results. the new features include the following: The PageRouteHandler class is a simple HTTP handler that you use when you define routes. You no longer have to write a custom route handler. The HttpRequest.RequestContext and Page.RouteData properties make it easier to access information that is passed in URL parameters. The RouteUrl expression provides a simple way to create a routed URL in markup. The RouteValue expression provides a simple way to extract URL parameter values in markup. The RouteParameter class makes it easier to pass URL parameter values to a query for a data source control (similar to FormParameter). You no longer have to change the Web.config file to enable routing. For more information about routing, see the following topics: ASP.NET Routing Walkthrough: Using ASP.NET Routing in a Web Forms Application How to: Define Routes for Web Forms Applications How to: Construct URLs from Routes How to: Access URL Parameters in a Routed Page Setting Client IDs The new ClientIDMode property makes it easier to write client script that references HTML elements rendered for server controls. Increasing use of Microsoft Ajax makes the need to do this more common. For example, you may have a data control that renders a long list of products with prices and you want to use client script to make a Web service call and update individual prices in the list as they change without refreshing the entire page. Typically you get a reference to an HTML element in client script by using the document.GetElementById method. You pass to this method the value of the id attribute of the HTML element you want to reference. In the case of elements that are rendered for ASP.NET server controls earlier versions of ASP.NET could make this difficult or impossible. You were not always able to predict what id values ASP.NET would generate, or ASP.NET could generate very long id values. The problem was especially difficult for data controls that would generate multiple rows for a single instance of the control in your markup. ASP.NET 4 adds two new algorithms for generating id attributes. These algorithms can generate id attributes that are easier to work with in client script because they are more predictable and that are easier to work with because they are simpler. For more information about how to use the new algorithms, see the following topics: ASP.NET Web Server Control Identification Walkthrough: Making Data-Bound Controls Easier to Access from JavaScript Walkthrough: Making Controls Located in Web User Controls Easier to Access from JavaScript How to: Access Controls from JavaScript by ID Persisting Row Selection in Data Controls The GridView and ListView controls enable users to select a row. In previous versions of ASP.NET, row selection was based on the row index on the page. For example, if you select the third item on page 1 and then move to page 2, the third item on page 2 is selected. In most cases, is more desirable not to select any rows on page 2. ASP.NET 4 supports Persisted Selection, a new feature that was initially supported only in Dynamic Data projects in the .NET Framework 3.5 SP1. When this feature is enabled, the selected item is based on the row data key. This means that if you select the third row on page 1 and move to page 2, nothing is selected on page 2. When you move back to page 1, the third row is still selected. This is a much more natural behavior than the behavior in earlier versions of ASP.NET. Persisted selection is now supported for the GridView and ListView controls in all projects. You can enable this feature in the GridView control, for example, by setting the EnablePersistedSelection property, as shown in the following example: <asp:GridView id="GridView2" runat="server" PersistedSelection="true"> </asp:GridView> FormView Control Enhancements The FormView control is enhanced to make it easier to style the content of the control with CSS. In previous versions of ASP.NET, the FormView control rendered it contents using an item template. This made styling more difficult in the markup because unexpected table row and table cell tags were rendered by the control. The FormView control supports RenderOuterTable, a property in ASP.NET 4. When this property is set to false, as show in the following example, the table tags are not rendered. This makes it easier to apply CSS style to the contents of the control. <asp:FormView ID="FormView1" runat="server" RenderTable="false"> For more information, see FormView Web Server Control Overview. ListView Control Enhancements The ListView control, which was introduced in ASP.NET 3.5, has all the functionality of the GridView control while giving you complete control over the output. This control has been made easier to use in ASP.NET 4. The earlier version of the control required that you specify a layout template that contained a server control with a known ID. The following markup shows a typical example of how to use the ListView control in ASP.NET 3.5. <asp:ListView ID="ListView1" runat="server"> <LayoutTemplate> <asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder> </LayoutTemplate> <ItemTemplate> <% Eval("LastName")%> </ItemTemplate> </asp:ListView> In ASP.NET 4, the ListView control does not require a layout template. The markup shown in the previous example can be replaced with the following markup: <asp:ListView ID="ListView1" runat="server"> <ItemTemplate> <% Eval("LastName")%> </ItemTemplate> </asp:ListView> For more information, see ListView Web Server Control Overview. Filtering Data with the QueryExtender Control A very common task for developers who create data-driven Web pages is to filter data. This traditionally has been performed by building Where clauses in data source controls. This approach can be complicated, and in some cases the Where syntax does not let you take advantage of the full functionality of the underlying database. To make filtering easier, a new QueryExtender control has been added in ASP.NET 4. This control can be added to EntityDataSource or LinqDataSource controls in order to filter the data returned by these controls. Because the QueryExtender control relies on LINQ, but you do not to need to know how to write LINQ queries to use the query extender. The QueryExtender control supports a variety of filter options. The following lists QueryExtender filter options. Term Definition SearchExpression Searches a field or fields for string values and compares them to a specified string value. RangeExpression Searches a field or fields for values in a range specified by a pair of values. PropertyExpression Compares a specified value to a property value in a field. If the expression evaluates to true, the data that is being examined is returned. OrderByExpression Sorts data by a specified column and sort direction. CustomExpression Calls a function that defines custom filter in the page. For more information, see QueryExtenderQueryExtender Web Server Control Overview. Enhanced Support for Web Standards and Accessibility Earlier versions of ASP.NET controls sometimes render markup that does not conform to HTML, XHTML, or accessibility standards. ASP.NET 4 eliminates most of these exceptions. For details about how the HTML that is rendered by each control meets accessibility standards, see ASP.NET Controls and Accessibility. CSS for Controls that Can be Disabled In ASP.NET 3.5, when a control is disabled (see WebControl.Enabled), a disabled attribute is added to the rendered HTML element. For example, the following markup creates a Label control that is disabled: <asp:Label id="Label1" runat="server"   Text="Test" Enabled="false" /> In ASP.NET 3.5, the previous control settings generate the following HTML: <span id="Label1" disabled="disabled">Test</span> In HTML 4.01, the disabled attribute is not considered valid on span elements. It is valid only on input elements because it specifies that they cannot be accessed. On display-only elements such as span elements, browsers typically support rendering for a disabled appearance, but a Web page that relies on this non-standard behavior is not robust according to accessibility standards. For display-only elements, you should use CSS to indicate a disabled visual appearance. Therefore, by default ASP.NET 4 generates the following HTML for the control settings shown previously: <span id="Label1" class="aspNetDisabled">Test</span> You can change the value of the class attribute that is rendered by default when a control is disabled by setting the DisabledCssClass property. CSS for Validation Controls In ASP.NET 3.5, validation controls render a default color of red as an inline style. For example, the following markup creates a RequiredFieldValidator control: <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   ErrorMessage="Required Field" ControlToValidate="RadioButtonList1" /> ASP.NET 3.5 renders the following HTML for the validator control: <span id="RequiredFieldValidator1"   style="color:Red;visibility:hidden;">RequiredFieldValidator</span> By default, ASP.NET 4 does not render an inline style to set the color to red. An inline style is used only to hide or show the validator, as shown in the following example: <span id="RequiredFieldValidator1"   style"visibility:hidden;">RequiredFieldValidator</span> Therefore, ASP.NET 4 does not automatically show error messages in red. For information about how to use CSS to specify a visual style for a validation control, see Validating User Input in ASP.NET Web Pages. CSS for the Hidden Fields Div Element ASP.NET uses hidden fields to store state information such as view state and control state. These hidden fields are contained by a div element. In ASP.NET 3.5, this div element does not have a class attribute or an id attribute. Therefore, CSS rules that affect all div elements could unintentionally cause this div to be visible. To avoid this problem, ASP.NET 4 renders the div element for hidden fields with a CSS class that you can use to differentiate the hidden fields div from others. The new classvalue is shown in the following example: <div class="aspNetHidden"> CSS for the Table, Image, and ImageButton Controls By default, in ASP.NET 3.5, some controls set the border attribute of rendered HTML to zero (0). The following example shows HTML that is generated by the Table control in ASP.NET 3.5: <table id="Table2" border="0"> The Image control and the ImageButton control also do this. Because this is not necessary and provides visual formatting information that should be provided by using CSS, the attribute is not generated in ASP.NET 4. CSS for the UpdatePanel and UpdateProgress Controls In ASP.NET 3.5, the UpdatePanel and UpdateProgress controls do not support expando attributes. This makes it impossible to set a CSS class on the HTMLelements that they render. In ASP.NET 4 these controls have been changed to accept expando attributes, as shown in the following example: <asp:UpdatePanel runat="server" class="myStyle"> </asp:UpdatePanel> The following HTML is rendered for this markup: <div id="ctl00_MainContent_UpdatePanel1" class="expandoclass"> </div> Eliminating Unnecessary Outer Tables In ASP.NET 3.5, the HTML that is rendered for the following controls is wrapped in a table element whose purpose is to apply inline styles to the entire control: FormView Login PasswordRecovery ChangePassword If you use templates to customize the appearance of these controls, you can specify CSS styles in the markup that you provide in the templates. In that case, no extra outer table is required. In ASP.NET 4, you can prevent the table from being rendered by setting the new RenderOuterTable property to false. Layout Templates for Wizard Controls In ASP.NET 3.5, the Wizard and CreateUserWizard controls generate an HTML table element that is used for visual formatting. In ASP.NET 4 you can use a LayoutTemplate element to specify the layout. If you do this, the HTML table element is not generated. In the template, you create placeholder controls to indicate where items should be dynamically inserted into the control. (This is similar to how the template model for the ListView control works.) For more information, see the Wizard.LayoutTemplate property. New HTML Formatting Options for the CheckBoxList and RadioButtonList Controls ASP.NET 3.5 uses HTML table elements to format the output for the CheckBoxList and RadioButtonList controls. To provide an alternative that does not use tables for visual formatting, ASP.NET 4 adds two new options to the RepeatLayout enumeration: UnorderedList. This option causes the HTML output to be formatted by using ul and li elements instead of a table. OrderedList. This option causes the HTML output to be formatted by using ol and li elements instead of a table. For examples of HTML that is rendered for the new options, see the RepeatLayout enumeration. Header and Footer Elements for the Table Control In ASP.NET 3.5, the Table control can be configured to render thead and tfoot elements by setting the TableSection property of the TableHeaderRow class and the TableFooterRow class. In ASP.NET 4 these properties are set to the appropriate values by default. CSS and ARIA Support for the Menu Control In ASP.NET 3.5, the Menu control uses HTML table elements for visual formatting, and in some configurations it is not keyboard-accessible. ASP.NET 4 addresses these problems and improves accessibility in the following ways: The generated HTML is structured as an unordered list (ul and li elements). CSS is used for visual formatting. The menu behaves in accordance with ARIA standards for keyboard access. You can use arrow keys to navigate menu items. (For information about ARIA, see Accessibility in Visual Studio and ASP.NET.) ARIA role and property attributes are added to the generated HTML. (Attributes are added by using JavaScript instead of included in the HTML, to avoid generating HTML that would cause markup validation errors.) Styles for the Menu control are rendered in a style block at the top of the page, instead of inline with the rendered HTML elements. If you want to use a separate CSS file so that you can modify the menu styles, you can set the Menu control's new IncludeStyleBlock property to false, in which case the style block is not generated. Valid XHTML for the HtmlForm Control In ASP.NET 3.5, the HtmlForm control (which is created implicitly by the <form runat="server"> tag) renders an HTML form element that has both name and id attributes. The name attribute is deprecated in XHTML 1.1. Therefore, this control does not render the name attribute in ASP.NET 4. Maintaining Backward Compatibility in Control Rendering An existing ASP.NET Web site might have code in it that assumes that controls are rendering HTML the way they do in ASP.NET 3.5. To avoid causing backward compatibility problems when you upgrade the site to ASP.NET 4, you can have ASP.NET continue to generate HTML the way it does in ASP.NET 3.5 after you upgrade the site. To do so, you can set the controlRenderingCompatibilityVersion attribute of the pages element to "3.5" in the Web.config file of an ASP.NET 4 Web site, as shown in the following example: <system.web>   <pages controlRenderingCompatibilityVersion="3.5"/> </system.web> If this setting is omitted, the default value is the same as the version of ASP.NET that the Web site targets. (For information about multi-targeting in ASP.NET, see .NET Framework Multi-Targeting for ASP.NET Web Projects.) ASP.NET MVC ASP.NET MVC helps Web developers build compelling standards-based Web sites that are easy to maintain because it decreases the dependency among application layers by using the Model-View-Controller (MVC) pattern. MVC provides complete control over the page markup. It also improves testability by inherently supporting Test Driven Development (TDD). Web sites created using ASP.NET MVC have a modular architecture. This allows members of a team to work independently on the various modules and can be used to improve collaboration. For example, developers can work on the model and controller layers (data and logic), while the designer work on the view (presentation). For tutorials, walkthroughs, conceptual content, code samples, and a complete API reference, see ASP.NET MVC 2. Dynamic Data Dynamic Data was introduced in the .NET Framework 3.5 SP1 release in mid-2008. This feature provides many enhancements for creating data-driven applications, such as the following: A RAD experience for quickly building a data-driven Web site. Automatic validation that is based on constraints defined in the data model. The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project. For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. For more information, see ASP.NET Dynamic Data Content Map. Enabling Dynamic Data for Individual Data-Bound Controls in Existing Web Applications You can use Dynamic Data features in existing ASP.NET Web applications that do not use scaffolding by enabling Dynamic Data for individual data-bound controls. Dynamic Data provides the presentation and data layer support for rendering these controls. When you enable Dynamic Data for data-bound controls, you get the following benefits: Setting default values for data fields. Dynamic Data enables you to provide default values at run time for fields in a data control. Interacting with the database without creating and registering a data model. Automatically validating the data that is entered by the user without writing any code. For more information, see Walkthrough: Enabling Dynamic Data in ASP.NET Data-Bound Controls. New Field Templates for URLs and E-mail Addresses ASP.NET 4 introduces two new built-in field templates, EmailAddress.ascx and Url.ascx. These templates are used for fields that are marked as EmailAddress or Url using the DataTypeAttribute attribute. For EmailAddress objects, the field is displayed as a hyperlink that is created by using the mailto: protocol. When users click the link, it opens the user's e-mail client and creates a skeleton message. Objects typed as Url are displayed as ordinary hyperlinks. The following example shows how to mark fields. [DataType(DataType.EmailAddress)] public object HomeEmail { get; set; } [DataType(DataType.Url)] public object Website { get; set; } Creating Links with the DynamicHyperLink Control Dynamic Data uses the new routing feature that was added in the .NET Framework 3.5 SP1 to control the URLs that users see when they access the Web site. The new DynamicHyperLink control makes it easy to build links to pages in a Dynamic Data site. For information, see How to: Create Table Action Links in Dynamic Data Support for Inheritance in the Data Model Both the ADO.NET Entity Framework and LINQ to SQL support inheritance in their data models. An example of this might be a database that has an InsurancePolicy table. It might also contain CarPolicy and HousePolicy tables that have the same fields as InsurancePolicy and then add more fields. Dynamic Data has been modified to understand inherited objects in the data model and to support scaffolding for the inherited tables. For more information, see Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data. Support for Many-to-Many Relationships (Entity Framework Only) The Entity Framework has rich support for many-to-many relationships between tables, which is implemented by exposing the relationship as a collection on an Entity object. New field templates (ManyToMany.ascx and ManyToMany_Edit.ascx) have been added to provide support for displaying and editing data that is involved in many-to-many relationships. For more information, see Working with Many-to-Many Data Relationships in Dynamic Data. New Attributes to Control Display and Support Enumerations The DisplayAttribute has been added to give you additional control over how fields are displayed. The DisplayNameAttribute attribute in earlier versions of Dynamic Data enabled you to change the name that is used as a caption for a field. The new DisplayAttribute class lets you specify more options for displaying a field, such as the order in which a field is displayed and whether a field will be used as a filter. The attribute also provides independent control of the name that is used for the labels in a GridView control, the name that is used in a DetailsView control, the help text for the field, and the watermark used for the field (if the field accepts text input). The EnumDataTypeAttribute class has been added to let you map fields to enumerations. When you apply this attribute to a field, you specify an enumeration type. Dynamic Data uses the new Enumeration.ascx field template to create UI for displaying and editing enumeration values. The template maps the values from the database to the names in the enumeration. Enhanced Support for Filters Dynamic Data 1.0 had built-in filters for Boolean columns and foreign-key columns. The filters did not let you specify the order in which they were displayed. The new DisplayAttribute attribute addresses this by giving you control over whether a column appears as a filter and in what order it will be displayed. An additional enhancement is that filtering support has been rewritten to use the new QueryExtender feature of Web Forms. This lets you create filters without requiring knowledge of the data source control that the filters will be used with. Along with these extensions, filters have also been turned into template controls, which lets you add new ones. Finally, the DisplayAttribute class mentioned earlier allows the default filter to be overridden, in the same way that UIHint allows the default field template for a column to be overridden. For more information, see Walkthrough: Filtering Rows in Tables That Have a Parent-Child Relationship and QueryableFilterRepeater. ASP.NET Chart Control The ASP.NET chart server control enables you to create ASP.NET pages applications that have simple, intuitive charts for complex statistical or financial analysis. The chart control supports the following features: Data series, chart areas, axes, legends, labels, titles, and more. Data binding. Data manipulation, such as copying, splitting, merging, alignment, grouping, sorting, searching, and filtering. Statistical formulas and financial formulas. Advanced chart appearance, such as 3-D, anti-aliasing, lighting, and perspective. Events and customizations. Interactivity and Microsoft Ajax. Support for the Ajax Content Delivery Network (CDN), which provides an optimized way for you to add Microsoft Ajax Library and jQuery scripts to your Web applications. For more information, see Chart Web Server Control Overview. Visual Web Developer Enhancements The following sections provide information about enhancements and new features in Visual Studio 2010 and Visual Web Developer Express. The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup snippets, and features a redesigned version of IntelliSense for JScript. Improved CSS Compatibility The Visual Web Developer designer in Visual Studio 2010 has been updated to improve CSS 2.1 standards compliance. The designer better preserves HTML source code and is more robust than in previous versions of Visual Studio. HTML and JScript Snippets In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes whole tags and more. In Visual Studio 2010, IntelliSense snippets are supported for JScript, alongside C# and Visual Basic, which were supported in earlier versions of Visual Studio. Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat="server") and common attributes specific to a tag (such as ID, DataSourceID, ControlToValidate, and Text). You can download additional snippets, or you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks. For more information on HTML snippets, see Walkthrough: Using HTML Snippets. JScript IntelliSense Enhancements In Visual 2010, JScript IntelliSense has been redesigned to provide an even richer editing experience. IntelliSense now recognizes objects that have been dynamically generated by methods such as registerNamespace and by similar techniques used by other JavaScript frameworks. Performance has been improved to analyze large libraries of script and to display IntelliSense with little or no processing delay. Compatibility has been significantly increased to support almost all third-party libraries and to support diverse coding styles. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense. Web Application Deployment with Visual Studio 2010 For Web application projects, Visual Studio now provides tools that work with the IIS Web Deployment Tool (Web Deploy) to automate many processes that had to be done manually in earlier versions of ASP.NET. For example, the following tasks can now be automated: Creating an IIS application on the destination computer and configuring IIS settings. Copying files to the destination computer. Changing Web.config settings that must be different in the destination environment. Propagating changes to data or data structures in SQL Server databases that are used by the Web application. For more information about Web application deployment, see ASP.NET Deployment Content Map. Enhancements to ASP.NET Multi-Targeting ASP.NET 4 adds new features to the multi-targeting feature to make it easier to work with projects that target earlier versions of the .NET Framework. Multi-targeting was introduced in ASP.NET 3.5 to enable you to use the latest version of Visual Studio without having to upgrade existing Web sites or Web services to the latest version of the .NET Framework. In Visual Studio 2008, when you work with a project targeted for an earlier version of the .NET Framework, most features of the development environment adapt to the targeted version. However, IntelliSense displays language features that are available in the current version, and property windows display properties available in the current version. In Visual Studio 2010, only language features and properties available in the targeted version of the .NET Framework are shown. For more information about multi-targeting, see the following topics: .NET Framework Multi-Targeting for ASP.NET Web Projects ASP.NET Side-by-Side Execution Overview How to: Host Web Applications That Use Different Versions of the .NET Framework on the Same Server How to: Deploy Web Site Projects Targeted for Earlier Versions of the .NET Framework

    Read the article

  • Hierarchical View/ViewModel/Presenters in MVPVM

    - by Brian Flynn
    I've been working with MVVM for a while, but I've recently started using MVPVM and I want to know how to create hierarchial View/ViewModel/Presenter app using this pattern. In MVVM I would typically build my application using a hierarchy of Views and corresponding ViewModels e.g. I might define 3 views as follows: The View Models for these views would be as follows: public class AViewModel { public string Text { get { return "This is A!"; } } public object Child1 { get; set; } public object Child2 { get; set; } } public class BViewModel { public string Text { get { return "This is B!"; } } } public class CViewModel { public string Text { get { return "This is C!"; } } } In would then have some data templates to say that BViewModel and CViewModel should be presented using View B and View C: <DataTemplate DataType="{StaticResource local:BViewModel}"> <local:BView/> </DataTemplate> <DataTemplate DataType="{StaticResource local:CViewModel}"> <local:CView/> </DataTemplate> The final step would be to put some code in AViewModel that would assign values to Child1 and Child2: public AViewModel() { this.Child1 = new AViewModel(); this.Child2 = new BViewModel(); } The result of all this would be a screen that looks something like: Doing this in MVPVM would be fairly simple - simply moving the code in AViewModel's constructor to APresenter: public class APresenter { .... public void WireUp() { ViewModel.Child1 = new BViewModel(); ViewModel.Child2 = new CViewModel(); } } But If I want to have business logic for BViewModel and CViewModel I would need to have a BPresenter and a CPresenter - the problem is, Im not sure where the best place to put these are. I could store references to the presenter for AViewModel.Child1 and AViewModel.Child2 in APresenter i.e.: public class APresenter : IPresenter { private IPresenter child1Presenter; private IPresenter child2Presenter; public void WireUp() { child1Presenter = new BPresenter(); child1Presenter.WireUp(); child2Presenter = new CPresenter(); child2Presenter.WireUp(); ViewModel.Child1 = child1Presenter.ViewModel; ViewModel.Child2 = child2Presenter.ViewModel; } } But this solution seems inelegant compared to the MVVM approach. I have to keep track of both the presenter and the view model and ensure they stay in sync. If, for example, I wanted a button on View A, which, when clicked swapped the View's in Child1 and Child2, I might have a command that did the following: var temp = ViewModel.Child1; ViewModel.Child1 = ViewModel.Child2; ViewModel.Child2 = temp; This would work as far as swapping the view's on screen (assuming the correct Property Change notification code is in place), but now my APresenter.child1Presenter is pointing to the presenter for AViewModel.Child2, and APresenter.child2Presenter is pointing to the presenter for AViewModel.Child1. If something accesses APresenter.child1Presenter, any changes will actually happen to AViewModel.Child2. I can imagine this leading to all sorts of debugging fun. I know that I may be misunderstanding the pattern, and if this is the case a clarification of what Im doing wrong would be appreciated.

    Read the article

  • [EF + Oracle] Entities

    - by JTorrecilla
    Prologue Following with the Serie I started yesterday about Entity Framework with Oracle, Today I am going to start talking about Entities. What is an Entity? A Entity is an object of the EF model corresponding to a record in a DB table. For example, let’s see, in Image 1 we can see one Entity from our model, and in the second one we can see the mapping done with the DB. (Image 1) (Image 2) More in depth a Entity is a Class inherited from the abstract class “EntityObject”, contained by the “System.Data.Objects.DataClasses” namespace. At the same time, this class inherits from the following Class and interfaces: StructuralObject: It is an Abstract class that inherits from INotifyPropertyChanging and INotifyPropertyChanged interfaces, and it exposes the events that manage the Changes of the class, and the functions related to check the data types of the Properties from our Entity.  IEntityWithKey: Interface which exposes the Key of the entity. IEntityWithChangeTracker: Interface which lets indicate the state of the entity (Detached, Modified, Added…) IEntityWithRelationships: Interface which indicates the relations about the entity. Which is the Content of a Entity? A Entity is composed by: Properties, Navigation Properties and Methods. What is a Property? A Entity Property is an object that represents a column from the mapped table from DB. It has a data type equivalent in .Net Framework to the DB Type. When we create the EF model, VS, internally, create the code for each Entity selected in the Tables step, such all methods that we will see in next steps. For each property, VS creates a structure similar to: · Private variable with the mapped Data type. · Function with a name like On{Property_Name}Changing({dataType} value): It manages the event which happens when we try to change the value. · Function with a name like On{Property_Name}Change: It manages the event raised when the property has changed successfully. · Property with Get and Set methods: The Set Method manages the private variable and do the following steps: Raise Changing event. Report the Entity is Changing. Set the prívate variable. For it, Use the SetValidValue function of the StructuralObject. There is a function for each datatype, and the functions takes 2 params: the value, and if the prop allow nulls. Invoke that the entity has been successfully changed. Invoke the Changed event of the Prop. ReportPropertyChanging and ReportPropertyChanged events, let, respectively, indicate that there is pending changes in the Entity, and the changes have success correctly. While the ReportPropertyChanged is raised, the Track State of the Entity will be changed. What is a Navigation Property? Navigation Properties are a kind of property of the type: EntityCollection<TEntity>, where TEntity is an Entity type from the model related with the current one, it is said, is a set of record from a related table in the DB. The EntityCollection class inherits from: · RelatedEnd: There is an abstract class that give the functions needed to obtein the related objects. · ICollection<TEntity> · IEnumerable<TEntity> · IEnumerable · IListSource For the previous interfaces, I wish recommend the following post from Jose Miguel Torres. Navigation properties allow us, to get and query easily objects related with the Entity. Methods? There is only one method in the Entity object. “Create{Entity}”, that allow us to create an object of the Entity by sending the parameters needed to create it. Finally After this chapter, we know what is an Entity, how is related to the DB and the relation to other Entities. In following chapters, we will se CRUD operations(Create, Read, Update, Delete).

    Read the article

  • SQL SERVER – Asynchronous Update and Timestamp – Check if Row Values are Changed Since Last Retrieve

    - by pinaldave
    Here is the question received just this morning. “Pinal, Our application is much different than other application you might have come across. In simple words, I would like to call it Asynchronous Updated Application. We need your quick opinion about one of the situation which we are facing. From business side: We have bidding system (similar to eBay but not exactly) and where multiple parties bid on one item, during the last few minutes of bidding many parties try to bid at the same time with the same price. When they hit submit, we would like to check if the original data which they retrieved is changed or not. If the original data which they have retrieved is the same, we will accept their new proposed price. If original data are changed, they will have to resubmit the data with new price. From technical side: We have a row which we retrieve in our application. Multiple users are retrieving the same row. Some of the users will update the value of the row and submit. However, only the very first user should be allowed to update the row and remaining all the users will have to re-fetch the row and updated it once again. We do not want to lock any record as that will create other problems. Do you have any solution for this kind of situation?” Fantastic Question. I believe there is good chance that we can use timestamp datatype in this kind of application. Before we continue let us see following simple example. USE tempdb GO CREATE TABLE SampleTable (ID INT, Col1 VARCHAR(100), TimeStampCol TIMESTAMP) GO INSERT INTO SampleTable (ID, Col1) VALUES (1, 'FirstVal') GO SELECT ID, Col1, TimeStampCol FROM SampleTable st GO UPDATE SampleTable SET Col1 = 'NextValue' GO SELECT ID, Col1, TimeStampCol FROM SampleTable st GO DROP TABLE SampleTable GO Now let us see the resultset. Here is the simple explanation of the scenario. We created a table with simple column with TIMESTAMP datatype. When we inserted a very first value the timestamp was generated. When we updated any value in that row, the timestamp was updated with the new value. Every single time when we update any value in the row, it will generate new timestamp value. Now let us apply this in an original question’s scenario. In that case multiple users are retrieving the same row. Everybody will have the same now same TimeStamp with them. Before any user update any value they should once again retrieve the timestamp from the table and compare with the timestamp they have with them. If both of the timestamp have the same value – the original row has not been updated and we can safely update the row with the new value. After initial update, now the row will contain a new timestamp. Any subsequent update to the same row should also go to the same process of checking the value of the timestamp they have in their memory. In this case, the timestamp from memory will be different from the timestamp in the row. This indicates that row in the table has changed and new updates should not be allowed. I believe timestamp can be very very useful in this kind of scenario. Is there any better alternative? Please leave a comment with the suggestion and I will post on the blog with due credit. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • JQuery Json error: Object doesn't support this property or method

    - by Abu Hamzah
    ERROR: Microsoft JScript runtime error: Object doesn't support this property or method i am using WCF service to pull the data and its very simple for the purpose of test and it does returning me the data from wcf service but it fails on json2.js on line number 314-316 // We split the first stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace all backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { here is what i am doing function serviceProxy(wjOrderServiceURL) { var _I = this; this.ServiceURL = wjOrderServiceURL; // *** Call a wrapped object this.invoke = function (options) { // Default settings var settings = { serviceMethod: '', data: null, callback: null, error: null, type: "POST", processData: false, contentType: "application/json", dataType: "text", bare: false }; if (options) { $.extend(settings, options); } function GetFederalHolidays() { $("#dContacts1").empty().html('Searching for Active Contacts...'); ContactServiceProxy.invoke({ serviceMethod: "Holidays", callback: function (response) { // ProcessActiveContacts1(response); debugger }, error: function (xhr, errorMsg, thrown) { postErrorAndUnBlockUI(xhr, errorMsg, thrown); } }); } any help what iam doing wrong? i try to change from dataType: text to json but i get the same error above.

    Read the article

  • How to create a MVC 2 DisplayTemplate for a field whose display format is dependent on another field

    - by Glenn
    If I have a property whose display format is dependent on the value of another property in the view model how do I create a display template for it? The combination of field1's display being dependent on field2's value will be used throughout the app and I would like to encapsulate this in a MVC 2 display template. To be more specific, I've already create a display template (Social.ascx) for custom data type Social that masks a social security number for display. For instance, XXX-XX-1234. [DataType("Social")] public string SocialSecurityNumber { get; set; } All employees also have an employeeID. Certain companies use the employee's social security number as either the whole employee id or as part of it. I need to also mask the employeeID if it contains the social. I'd like to create another display template (EmpID.ascx) to perform this task. [DataType("EmpID")] public string EmployeeID { get; set; } The problem is that I don't know how to get both properties in the "EmpID" template to be able to perform the comparison. Thanks for the help.

    Read the article

  • How to do server-side validation using Jqgrid?

    - by Eoghan
    Hi, I'm using jqgrid to display a list of sites and I want to do some server side validation when a site is added or edited. (Form editing rather than inline. Validation needs to be server side for various reasons I won't go into.) I thought the best way would be to check the data via an ajax request when the beforeSubmit event is triggered. However this only seems to work when I'm editing an existing row in the grid - the function isn't called when I add a new row. Have I got my beforeSubmit in the wrong place? Thanks for your help. $("#sites-grid").jqGrid({ url:'/json/sites', datatype: "json", mtype: 'GET', colNames:['Code', 'Name', 'Area', 'Cluster', 'Date Live', 'Status', 'Lat', 'Lng'], colModel :[ {name:'code', index:'code', width:80, align:'left', editable:true}, {name:'name', index:'name', width:250, align:'left', editrules:{required:true}, editable:true}, {name:'area', index:'area', width:60, align:'left', editable:true}, {name:'cluster_id', index:'cluster_id', width:80, align:'right', editrules:{required:true, integer:true}, editable:true, edittype:"select", editoptions:{value:"<?php echo $cluster_options; ?>"}}, {name:'estimated_live_date', index:'estimated_live_date', width:120, align:'left', editable:true, editrules:{required:true}, edittype:"select", editoptions:{value:"<?php echo $this->month_options; ?>"}}, {name:'status', index:'status', width:80, align:'left', editable:true, edittype:"select", editoptions:{value:"Live:Live;Plan:Plan;"}}, {name:'lat', index:'lat', width:140, align:'right', editrules:{required:true}, editable:true}, {name:'lng', index:'lng', width:140, align:'right', editrules:{required:true}, editable:true}, ], height: '300', pager: '#pager-sites', rowNum:30, rowList:[10,30,90], sortname: 'cluster_id', sortorder: 'desc', viewrecords: true, multiselect: false, caption: 'Sites', editurl: '/json/sites' }); $("#sites-grid").jqGrid('navGrid','#pager-sites',{edit:true,add:true,del:true, beforeSubmit : function(postdata, formid) { $.ajax({ url : 'json/validate-site/', data : postdata, dataType : 'json', type : 'post', success : function(data) { alert(data.message); return[data.result, data.message]; } }); }});

    Read the article

  • Model validation with enumerable properties in Asp.net MVC2 RTM

    - by Robert Koritnik
    I'm using DataAnnotations attributes to validate my model objects. My model class looks similar to this: public class MyModel { [Required] public string Title { get; set; } [Required] public List<User> Editors { get; set; } } public class User { public int Id { get; set; } [Required] public string FullName { get; set; } [Required] [DataType(DataType.Email)] public string Email { get; set; } } My controller action looks like: public ActionResult NewItem(MyModel data) { //... } User is presented with a view that has a form with: a text box with dummy name where users enter user's names. For each user they enter, there's a client script coupled with ajax that creates an <input type="hidden" name="data.Editors[0].Id" value="userId" /> for each user entered (enumeration index is therefore not always 0 as written here), so default model binder is able to consume and bind the form without any problems. a text box where users enter the title Since I'm using Asp.net MVC 2 RTM which does model validation instead of input validation I don't know how to avoid validation errors. The thing is I have to use BindAttribute on my controller action. I would have to either provide a white or a black list of properties. It's always a better practice to provide a white list. It's also more future proof. The problem My form works fine, but I get validation errors about user's FullName and Email properties since they are not provided. I also shouldn't feed them to the client (via ajax when user enters user data), because email is personal contact data and is not shared between users. If there was just a single user reference on MyModel I would write [Bind(Include = "Title, Editor.Id")] But I have an enumeration of them. How do I provide Bind white list to work with my model?

    Read the article

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