Search Results

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

Page 9/59 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How can I define a constructor in an open generic type?

    - by Cort
    I am trying to create on open generic type that has a constructor to be used by derived types, but I either don't know how to do it or it is not possible -- not sure which. public struct DataType<T> : IDataType { private T myValue; private TypeState myState; private DataType<T>(T initialValue, TypeState state) { myValue = initialValue; myState = state; } } Any help much appreciated! Cort

    Read the article

  • OIM 11g notification framework

    - by Rajesh G Kumar
    OIM 11g has introduced an improved and template based Notifications framework. New release has removed the limitation of sending text based emails (out-of-the-box emails) and enhanced to support html features. New release provides in-built out-of-the-box templates for events like 'Reset Password', 'Create User Self Service' , ‘User Deleted' etc. Also provides new APIs to support custom templates to send notifications out of OIM. OIM notification framework supports notification mechanism based on events, notification templates and template resolver. They are defined as follows: Ø Events are defined as XML file and imported as part of MDS database in order to make notification event available for use. Ø Notification templates are created using OIM advance administration console. The template contains the text and the substitution 'variables' which will be replaced with the data provided by the template resolver. Templates support internationalization and can be defined as HTML or in form of simple text. Ø Template resolver is a Java class that is responsible to provide attributes and data to be used at runtime and design time. It must be deployed following the OIM plug-in framework. Resolver data provided at design time is to be used by end user to design notification template with available entity variables and it also provides data at runtime to replace the designed variable with value to be displayed to recipients. Steps to define custom notifications in OIM 11g are: Steps# Steps 1. Define the Notification Event 2. Create the Custom Template Resolver class 3. Create Template with notification contents to be sent to recipients 4. Create Event triggering spots in OIM 1. Notification Event metadata The Notification Event is defined as XML file which need to be imported into MDS database. An event file must be compliant with the schema defined by the notification engine, which is NotificationEvent.xsd. The event file contains basic information about the event.XSD location in MDS database: “/metadata/iam-features-notification/NotificationEvent.xsd”Schema file can be viewed by exporting file from MDS using weblogicExportMetadata.sh script.Sample Notification event metadata definition: 1: <?xml version="1.0" encoding="UTF-8"?> 2: <Events xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="../../../metadata/NotificationEvent.xsd"> 3: <EventType name="Sample Notification"> 4: <StaticData> 5: <Attribute DataType="X2-Entity" EntityName="User" Name="Granted User"/> 6: </StaticData> 7: <Resolver class="com.iam.oim.demo.notification.DemoNotificationResolver"> 8: <Param DataType="91-Entity" EntityName="Resource" Name="ResourceInfo"/> 9: </Resolver> 10: </EventType> 11: </Events> Line# Description 1. XML file notation tag 2. Events is root tag 3. EventType tag is to declare a unique event name which will be available for template designing 4. The StaticData element lists a set of parameters which allow user to add parameters that are not data dependent. In other words, this element defines the static data to be displayed when notification is to be configured. An example of static data is the User entity, which is not dependent on any other data and has the same set of attributes for all event instances and notification templates. Available attributes are used to be defined as substitution tokens in the template. 5. Attribute tag is child tag for StaticData to declare the entity and its data type with unique reference name. User entity is most commonly used Entity as StaticData. 6. StaticData closing tag 7. Resolver tag defines the resolver class. The Resolver class must be defined for each notification. It defines what parameters are available in the notification creation screen and how those parameters are replaced when the notification is to be sent. Resolver class resolves the data dynamically at run time and displays the attributes in the UI. 8. The Param DataType element lists a set of parameters which allow user to add parameters that are data dependent. An example of the data dependent or a dynamic entity is a resource object which user can select at run time. A notification template is to be configured for the resource object. Corresponding to the resource object field, a lookup is displayed on the UI. When a user selects the event the call goes to the Resolver class provided to fetch the fields that are displayed in the Available Data list, from which user can select the attribute to be used on the template. Param tag is child tag to declare the entity and its data type with unique reference name. 9. Resolver closing tag 10 EventType closing tag 11. Events closing tag Note: - DataType needs to be declared as “X2-Entity” for User entity and “91-Entity” for Resource or Organization entities. The dynamic entities supported for lookup are user, resource, and organization. Once notification event metadata is defined, need to be imported into MDS database. Fully qualified resolver class name need to be define for XML but do not need to load the class in OIM yet (it can be loaded later). 2. Coding the notification resolver All event owners have to provide a resolver class which would resolve the data dynamically at run time. Custom resolver class must implement the interface oracle.iam.notification.impl.NotificationEventResolver and override the implemented methods with actual implementation. It has 2 methods: S# Methods Descriptions 1. public List<NotificationAttribute> getAvailableData(String eventType, Map<String, Object> params); This API will return the list of available data variables. These variables will be available on the UI while creating/modifying the Templates and would let user select the variables so that they can be embedded as a token as part of the Messages on the template. These tokens are replaced by the value passed by the resolver class at run time. Available data is displayed in a list. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the entity name and the corresponding value for which available data is to be fetched. Sample code snippet: List<NotificationAttribute> list = new ArrayList<NotificationAttribute>(); long objKey = (Long) params.get("resource"); //Form Field details based on Resource object key HashMap<String, Object> formFieldDetail = getObjectFormName(objKey); for (Iterator<?> itrd = formFieldDetail.entrySet().iterator(); itrd.hasNext(); ) { NotificationAttribute availableData = new NotificationAttribute(); Map.Entry formDetailEntrySet = (Entry<?, ?>)itrd.next(); String fieldLabel = (String)formDetailEntrySet.getValue(); availableData.setName(fieldLabel); list.add(availableData); } return list; 2. Public HashMap<String, Object> getReplacedData(String eventType, Map<String, Object> params); This API would return the resolved value of the variables present on the template at the runtime when notification is being sent. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the base values such as usr_key, obj_key etc required by the resolver implementation to resolve the rest of the variables in the template. Sample code snippet: HashMap<String, Object> resolvedData = new HashMap<String, Object>();String firstName = getUserFirstname(params.get("usr_key"));resolvedData.put("fname", firstName); String lastName = getUserLastName(params.get("usr_key"));resolvedData.put("lname", lastname);resolvedData.put("count", "1 million");return resolvedData; This code must be deployed as per OIM 11g plug-in framework. The XML file defining the plug-in is as below: <?xml version="1.0" encoding="UTF-8"?> <oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <plugins pluginpoint="oracle.iam.notification.impl.NotificationEventResolver"> <plugin pluginclass= " com.iam.oim.demo.notification.DemoNotificationResolver" version="1.0" name="Sample Notification Resolver"/> </plugins> </oimplugins> 3. Defining the template To create a notification template: Log in to the Oracle Identity Administration Click the System Management tab and then click the Notification tab From the Actions list on the left pane, select Create On the Create page, enter values for the following fields under the Template Information section: Template Name: Demo template Description Text: Demo template Under the Event Details section, perform the following: From the Available Event list, select the event for which the notification template is to be created from a list of available events. Depending on your selection, other fields are displayed in the Event Details section. Note that the template Sample Notification Event created in the previous step being used as the notification event. The contents of the Available Data drop down are based on the event XML StaticData tag, the drop down basically lists all the attributes of the entities defined in that tag. Once you select an element in the drop down, it will show up in the Selected Data text field and then you can just copy it and paste it into either the message subject or the message body fields prefixing $ symbol. Example if list has attribute like First_Name then message body will contains this as $First_Name which resolver will parse and replace it with actual value at runtime. In the Resource field, select a resource from the lookup. This is the dynamic data defined by the Param DataType element in the XML definition. Based on selected resource getAvailableData method of resolver will be called to fetch the resource object attribute detail, if method is overridden with required implementation. For current scenario, Map<String, Object> params will get populated with object key as value and key as “resource” in the map. This is the only input will be provided to resolver at design time. You need to implement the further logic to fetch the object attributes detail to populate the available Data list. List string should not have space in between, if object attributes has space for attribute name then implement logic to replace the space with ‘_’ before populating the list. Example if attribute name is “First Name” then make it “First_Name” and populate the list. Space is not supported while you try to parse and replace the token at run time with real value. Make a note that the Available Data and Selected Data are used in the substitution tokens definition only, they do not define the final data that will be sent in the notification. OIM will invoke the resolver class to get the data and make the substitutions. Under the Locale Information section, enter values in the following fields: To specify a form of encoding, select either UTF-8 or ASCII. In the Message Subject field, enter a subject for the notification. From the Type options, select the data type in which you want to send the message. You can choose between HTML and Text/Plain. In the Short Message field, enter a gist of the message in very few words. In the Long Message field, enter the message that will be sent as the notification with Available data token which need to be replaced by resolver at runtime. After you have entered the required values in all the fields, click Save. A message is displayed confirming the creation of the notification template. Click OK 4. Triggering the event A notification event can be triggered from different places in OIM. The logic behind the triggering must be coded and plugged into OIM. Examples of triggering points for notifications: Event handlers: post process notifications for specific data updates in OIM users Process tasks: to notify the users that a provisioning task was executed by OIM Scheduled tasks: to notify something related to the task The scheduled job has two parameters: Template Name: defines the notification template to be sent User Login: defines the user record that will provide the data to be sent in the notification Sample Code Snippet: public void execute(String templateName , String userId) { try { NotificationService notService = Platform.getService(NotificationService.class); NotificationEvent eventToSend=this.createNotificationEvent(templateName,userId); notService.notify(eventToSend); } catch (Exception e) { e.printStackTrace(); } } private NotificationEvent createNotificationEvent(String poTemplateName, String poUserId) { NotificationEvent event = new NotificationEvent(); String[] receiverUserIds= { poUserId }; event.setUserIds(receiverUserIds); event.setTemplateName(poTemplateName); event.setSender(null); HashMap<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("USER_LOGIN",poUserId); event.setParams(templateParams); return event; } public HashMap getAttributes() { return null; } public void setAttributes() {} }

    Read the article

  • jquery ajax call from link loaded with ajax

    - by Jay
    //deep linking $("document").ready(function(){ contM = $('#main-content'); contS = $('#second-content'); $(contM).hide(); $(contM).addClass('hidden'); $(contS).hide(); $(contS).addClass('hidden'); function loadURL(URL) { //console.log("loadURL: " + URL); $.ajax({ url: URL, type: "POST", dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contM).html(data); $(contM).animW(); } }); } // Event handlers $.address.init(function(event) { //console.log("init: " + $('[rel=address:' + event.value + ']').attr('href')); }).change(function(event) { $.ajax({ url: $('[rel=address:' + event.value + ']').attr('href'), type: "POST", dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contM).html(data); $(contM).animW(); }}); //console.log("change"); }) $('.update-main a').live('click', function(){ loadURL($(this).attr('href')); }); $(".update-second a").live('click', function() { var link = $(this); $.ajax({ url: link.attr("href"), dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contS).html(data); $(contS).animW(); }}); }); }); I'm using jquery and the 'addresses' plugin to load content with ajax and maintain pagination. The problem I'm having is some content loads with links which are intended to load content into a secondary window. I'm using the .live() method to allow jquery to listen for new links loaded into the primary content div. This works until the .ajax() method is called for these fresh links loaded with ajax, where the method begins, but follows the original link before data can be received. I'm assuming the problem is in the client-side scripting, but it may be a problem with the call made to the server. I'm using the wordpress loop to parse the url and generate the html loaded via jquery. Thanks for any tips!

    Read the article

  • help with grouping and sorting for TreeView in xaml

    - by danhotb
    I am having problems getting my head around grouping and sorting in xaml and hope someone can get me straightened out! I have creaed an xml file from a tree of files and folders (just like windows explorer) that can be serveral levels deep. I have bound a TreeView control to an xml datasource and it works great! It sorts everything alphabetically but ... I would like it to sort all folders first then all files, rather than folders listed with files, as it does now. the xml : if you load this to a treeviw it will display the two files before the folder because they are first in alpha-order. here is my code: <!-- This will contain the XML-data. --> <XmlDataProvider x:Key="xmlDP" XPath="*"> <x:XData> <Select_Project /> </x:XData> </XmlDataProvider> <!-- This HierarchicalDataTemplate will visualize all XML-nodes --> <HierarchicalDataTemplate DataType="project" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="folder" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="file" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <CollectionViewSource x:Key="projectView" Source="{StaticResource xmlDP}"> <CollectionViewSource.SortDescriptions> <!-- ADD SORT DESCRIPTION HERE --> </CollectionViewSource.SortDescriptions> </CollectionViewSource> <TreeView Margin="11,79.992,18,19.089" Name="tvProject" BorderThickness="1" FontSize="12" FontFamily="Verdana"> <TreeViewItem ItemsSource="{Binding Source={StaticResource xmlDP}, XPath=*}" Header="Project"/> </TreeView>

    Read the article

  • Best way to change jqGrid rowNum from ALL to -1 before pass to a web service

    - by Billyhole
    I'm looking to find the best way to allow users to choose to show ALL records in a jqGrid. I know that a -1 value passed for the rows parameter denotes ALL, but I want the word "ALL" not a -1 to appear in the rowList select element, ie. rowList: [15, 50, 100, 'ALL']. I'm passing the grid request to a web service which accepts an int for "rows", and I'm trying find how and when I should change the user selected value of "ALL" to a -1 before it gets sent to the web service. Below is my cleaned up grid code. I tried some various code blocks before my $.ajax in the datatype function. But most attempts just seemed like I have to be doing this the most convoluted way I possibly could. For example, datatype: function(postdata) { if ($("#gridTableAssets").jqGrid('getGridParam', 'rowNum') == 'ALL') { $("#gridTableAssets").appendPostData({ "rows": -1, "page": 1 }); } $.ajax({... But doing that seemed to cause the actual "page" GridParam to be nulled out on subsequent grid actions, forcing me handle that in other places. There just seems like this is something that would be frequently done out there and have clean way of doing it. Cleaned grid code: $("#gridTableAssets").jqGrid({ datatype: function(postdata) { $.ajax({ url: "/Service/Repository.asmx/GetAssets", data: JSON.stringify(postdata), type: 'POST', contentType: "application/json; charset=utf-8", error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }, success: function(msg) { var assetsGrid = $("#gridTableAssets")[0]; assetsGrid.addJSONData(JSON.parse(msg)); ... } }); }, ... pager: $('#pagerAssets'), rowNum: 15, rowList: [15, 50, 100, 'ALL'], ... onPaging: function(index, colindex, sortorder) { SessionKeepAlive(); } }); And here is the web service [WebMethod] public string GetAssetsOfAssetStructure(bool _search, int rows, int page, string sidx, string sord, string filters)

    Read the article

  • Avoid the collapsing effect on TreeView after updating data

    - by Manolete
    I have a TreeView used to display events. It works great, however every time new events are coming in and populating the tree collapse the tree again to the original position. That is very annoying when the refresh time is less than 1 second and it does not allow the user to interact with the items of the tree. Is there any way to avoid this behaviour? <TreeView Margin="1" BorderThickness="0" Name="eventsTree" ItemsSource="{Binding EventAlertContainers}" Background="#00000000" ScrollViewer.VerticalScrollBarVisibility="Auto" FontSize="14" VirtualizingStackPanel.IsVirtualizing="True"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type C:EventAlertContainer}" ItemsSource="{Binding EventAlerts}"> <StackPanel Orientation="Horizontal"> <Image Width="20" Height="20" Margin="3,0" Source="Resources\Process_info_32.png" /> <TextBlock FontWeight="Bold" FontSize="16" Text="{Binding Description}" /> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type C:EventAlert}" ItemsSource="{Binding Events}"> <StackPanel Orientation="Horizontal"> <Image Width="20" Height="20" Margin="0,0" Source="Resources\clock2_32.jpg" /> <TextBlock FontWeight="DemiBold" FontSize="14" Text="{Binding Name}" /> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type C:Event}"> <StackPanel Orientation="Horizontal"> <Image Width="20" Height="20" Margin="0,0" Source="Resources\Task_32.png" /> <StackPanel Orientation="Vertical"> <TextBlock FontSize="12" Text="{Binding Name}" /> </StackPanel> </StackPanel> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView>

    Read the article

  • Another IE Issue with AJAX

    - by Nik
    Alright, This code works in every browser except IE (again, to be expected). The code is supposed to refresh based on setInterval, and does so normally in all other browsers except IE, which just doesn't refresh. Can you spot the problem? var nick = document.getElementById("chatnick").value; var sessid = document.getElementById("sessid").value; var room = document.getElementById("roomid").value; function user_read() { $.ajax({ type: "GET", url: "methods.php", data: {method: "u", room: room}, dataType: "html", success: function (data, status, xhr) { $("#userwindow").html(data); setTimeout(user_read, 10000); } }); } function ajax_read() { $.ajax({ type: "GET", url: "methods.php", data: {method: "r", room: room}, dataType: "html", success: function (data, status, xhr) { $("#chatwindow").html(data); setTimeout(ajax_read, 400); } }); } function submit_msg() { var msg = document.getElementById("chatmsg").value; $.ajax({ type: "GET", url: "methods.php", data: {method: "w", room: room, m: msg, n: nick, sessid: sessid}, dataType: "html", success: function (data, status, xhr) { } }); document.getElementById("chatmsg").value = ""; } function keyup(arg1) { if (arg1 == 13) submit_msg(); } setTimeout(function(){ajax_read();}, 400); user_read();

    Read the article

  • Heavy Mysql operation & Time Constraints [closed]

    - by Rahul Jha
    There is a performance issue where that I have stuck with my application which is based on PHP & MySql. The application is for Data Migration where data has to be uploaded and after various processes (Cleaning from foreign characters, duplicate check, id generation) it has to be inserted into one central table and then to 5 different tables. There, an id is generated and that id has to be updated to central table. There are different sets of records and validation rules. The problem I am facing is that when I insert say(4K) rows file (containing 20 columns) it is working fine within 15 min it gets inserted everywhere. But, when I insert the same records again then at this time it is taking one hour to insert (ideally it should get inserted by marking earlier inserted data as duplicate). After going through the log file, I noticed is that there is a Mysql select statement where I am checking the duplicates and getting ID which are duplicates. Then I am calling a function inside for loop which is basically inserting records into 5 tables and updates id to central table. This Calling function is major time of whole process. P.S. The records has to be inserted record by record.. Kindly Suggest some solution.. //This is that sample code $query=mysql_query("SELECT DISTINCT p1.ID FROM table1 p1, table2 p2, table3 a WHERE p2.datatype =0 AND (p1.datatype =1 || p1.datatype=2) AND p2.ID =0 AND p1.ID = a.ID AND p1.coulmn1 = p2.column1 AND p1.coulmn2 = p2.coulmn2 AND a.coulmn3 = p2.column3"); $num=mysql_num_rows($query); for($i=0;$i<$num;$i++) { $f=mysql_result($query,$i,"ID"); //calling function RecordInsert($f); }

    Read the article

  • jQuery/ajax working on IIS5.1 but not IIS6

    - by Mikejh99
    I'm running a weird issue here. I have code that makes jquery ajax calls to a web service and dynamically adds controls using jquery. Everything works fine on my dev machine running IIS 5.1, but not when deployed to IIS 6. I'm using VS2010/ASP.Net 4.0, C#, jQuery 1.4.2 and jQuery UI 1.8.1. I'm using the same browser for each. It partially works though. The code will add the controls to the page, but they aren't visible until I click them (they aren't visible though). I thought this was a css issue, but the styles are there too. The ajax calls look like this: $.ajax({ url: "/WebServices/AssetManager.asmx/Assets", type: "POST", datatype: "json", async: false, data: "{'q':'" + req.term + "', 'type':'Condition'}", contentType: "application/javascript; charset=utf-8", success: function (data) { res($.map(data.d, function (item) { return { label: item.Name, value: item.Name, id: item.Id, datatype: item.DataType } })) } }) Changing the content-type makes the autocomplete fail. I've quadruple checked and all the paths are correct, there is no document footer enabled in IIS, and I'm not using IIS compression. Any idea why the page will display and work properly in IIS 5 but only partially in IIS 6? (If it failed completely, that'd make more sense!). Is it a jQuery or CSS issue?

    Read the article

  • How can I include DBNull as a value in my strongly typed dataset?

    - by Beska
    I've created a strongly typed dataset (MyDataSet) in my .NET app. For the sake of simplicity, we'll say it has one DataTable (MyDataTable), with one column (MyCol). MyCol has its DataType property set to "System.Int32", and its AllowDBNull property set to "true". I'd like to manually create a new row, and add it to this dataset. I create the row without a problem, with something like: MyDataSet.MyDataTableRow myRow = MySimpleDataSet.MyDataTable.NewItemRow(); Fine. However, when I try to set the value to DBNull: myRow.MyCol = DBNull.Value; I'm told that I can't do it...that it can't cast that to an int. This makes sense, in a way, since I've defined it to be an int...but then how can I get DBNull in there? Am I not supposed to be able to have DBNull in there? Isn't that what the AllowDBNull property is for? I'm obviously missing something fundemental. Can someone help explain what it is? EDIT: I also tried entering "int?" as the DataType, but Visual Studio throws an error when I enter it, saying that "Column requires a valid DataType."

    Read the article

  • Using complex where clause in NHibernate mapping layer

    - by JLevett
    I've used where clauses previously in the mapping layer to prevent certain records from ever getting into my application at the lowest level possible. (Mainly to prevent having to re-write lots of lines of code to filter out the unwanted records) These have been simple, one column queries, like so this.Where("Invisible = 0"); However a scenario has appeared which requires the use of an exists sql query. exists (select ep_.Id from [Warehouse].[dbo].EventPart ep_ where Id = ep_.EventId and ep_.DataType = 4 In the above case I would usually reference the parent table Event with a short name, i.e. event_.Id however as Nhibernate generates these short names dynamically it's impossible to know what it's going to be. So instead I tried using just Id, from above ep_ where Id = ep_.EventId When the code is run, because of the dynamic short names the EventPart table short name ep_ is has another short name prefixed to it, event0_.ep_ where event0_ refers to the parent table. This causes an SQL error because of the . in between event0_ and ep_ So in my EventMap I have the following this.Where("(exists (select ep_.Id from [isnapshot.Warehouse].[dbo].EventPart ep_ where Id = ep_.EventId and ep_.DataType = 4)"); but when it's generated it creates this select cast(count(*) as INT) as col_0_0_ from [isnapshot.Warehouse].[dbo].Event event0_ where (exists (select ep_.Id from [isnapshot.Warehouse].[dbo].EventPart event0_.ep_ where event0_.Id = ep_.EventId and ep_.DataType = 4) It has correctly added the event0_ to the Id Was the mapping layer where clause built to handle this and if so where am I going wrong?

    Read the article

  • Render different view depending on the type of the data

    - by Miau
    Hi there So lets suppose we have an action in a controller that looks a bit like this: public ViewResult SomeAction(int id) { var data = _someService.GetData(id); ... //create new view model based on the data here return View(viewModel); } What I m trying to figure out is the best way to render a diferent view based on the type fo the data. the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value so I could achieve what I m trying to do doing something kinda like this public ViewResult SomeAction(int id) { var data = _someService.GetData(id); //I m mapping fields to the viewModel here var viewModel = GetViewModel(data); swtich(data.DataType) case DataType.TypeOne: return View("TypeOne", viewModel); break; ... } But this does not seem to be the nicest way, (I dont event know if it would work) Is this the way to go? Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar) Cheers

    Read the article

  • C# asp.net EF MVC postgresql error 23505: Duplicate key violates unique constraint

    - by user2721755
    EDIT: It was issue with database table - dropping and recreating table id column did the work. Problem solved. I'm trying to build web application, that is connected to postgresql database. Results are displaying in view with Kendo UI. When I'm trying to add new row (with Kendo UI 'Add new record' button), I get error 23505: 'Duplicate key violates unique constraint'. My guess is, that EF takes id to insert from the beginning, not the last one, because after 35 (it's number of rows in table) tries - and errors - adding works perfectly. Can someone help me to understand, what's wrong? Model: using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MainConfigTest.Models { [Table("mainconfig", Schema = "public")] public class Mainconfig { [Column("id")] [Key] [Editable(false)] public int Id { get; set; } [Column("descr")] [Editable(true)] public string Descr { get; set; } [Column("hibversion")] [Required] [Editable(true)] public long Hibversion { get; set; } [Column("mckey")] [Required] [Editable(true)] public string Mckey { get; set; } [Column("valuexml")] [Editable(true)] public string Valuexml { get; set; } [Column("mcvalue")] [Editable(true)] public string Mcvalue { get; set; } } } Context: using System.Data.Entity; namespace MainConfigTest.Models { public class MainConfigContext : DbContext { public DbSet<Mainconfig> Mainconfig { get; set; } } } Controller: namespace MainConfigTest.Controllers { public class MainConfigController : Controller { #region Properties private Models.MainConfigContext db = new Models.MainConfigContext(); private string mainTitle = "Mainconfig (Kendo UI)"; #endregion #region Initialization public MainConfigController() { ViewBag.MainTitle = mainTitle; } #endregion #region Ajax [HttpGet] public JsonResult GetMainconfig() { int take = HttpContext.Request["take"] == null ? 5 : Convert.ToInt32(HttpContext.Request["take"]); int skip = HttpContext.Request["skip"] == null ? 0 : Convert.ToInt32(HttpContext.Request["skip"]); Array data = (from Models.Mainconfig c in db.Mainconfig select c).OrderBy(c => c.Id).ToArray().Skip(skip).Take(take).ToArray(); return Json(new Models.MainconfigResponse(data, db.Mainconfig.Count()), JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult Create() { try { Mainconfig itemToAdd = new Mainconfig() { Descr = Convert.ToString(HttpContext.Request["Descr"]), Hibversion = Convert.ToInt64(HttpContext.Request["Hibversion"]), Mckey = Convert.ToString(HttpContext.Request["Mckey"]), Valuexml = Convert.ToString(HttpContext.Request["Valuexml"]), Mcvalue = Convert.ToString(HttpContext.Request["Mcvalue"]) }; db.Mainconfig.Add(itemToAdd); db.SaveChanges(); return Json(new { Success = true }); } catch (InvalidOperationException ex) { return Json(new { Success = false, msg = ex }); } } //other methods } } Kendo UI script in view: <script type="text/javascript"> $(document).ready(function () { $("#config-grid").kendoGrid({ sortable: true, pageable: true, scrollable: false, toolbar: ["create"], editable: { mode: "popup" }, dataSource: { pageSize: 5, serverPaging: true, transport: { read: { url: '@Url.Action("GetMainconfig")', dataType: "json" }, update: { url: '@Url.Action("Update")', type: "Post", dataType: "json", complete: function (e) { $("#config-grid").data("kendoGrid").dataSource.read(); } }, destroy: { url: '@Url.Action("Delete")', type: "Post", dataType: "json" }, create: { url: '@Url.Action("Create")', type: "Post", dataType: "json", complete: function (e) { $("#config-grid").data("kendoGrid").dataSource.read(); } }, }, error: function (e) { if(e.Success == false) { this.cancelChanges(); } }, schema: { data: "Data", total: "Total", model: { id: "Id", fields: { Id: { editable: false, nullable: true }, Descr: { type: "string"}, Hibversion: { type: "number", validation: {required: true,}, }, Mckey: { type: "string", validation: { required: true, }, }, Valuexml:{ type: "string"}, Mcvalue: { type: "string" } } } } }, //end DataSource // generate columns etc. Mainconfig table structure: id serial NOT NULL, descr character varying(200), hibversion bigint NOT NULL, mckey character varying(100) NOT NULL, valuexml character varying(8000), mcvalue character varying(200), CONSTRAINT mainconfig_pkey PRIMARY KEY (id), CONSTRAINT mainconfig_mckey_key UNIQUE (mckey) Any help will be appreciated.

    Read the article

  • In WPF, Selecting ItemContainerStyle based on data bound content

    - by Bart Roozendaal
    In #WPF you have ItemTemplateSelectors. But, can you also select an ItemContainerStyle based on the datatype of a bound object? I am databinding a scatterview. I want to set some properties of the generated ScatterViewItems based on the object in their DataContext. A mechanism similar to ItemTemplateSelector for styles would be great. Is that at all possible? I am now binding to properties in the objects that I am displaying to get the effect, but that feels like overhead and too complex (and most importantly, something that our XU designers can't do by themselves). This is the XAML that I am using now. Your help is greatly appreciated. <s:ScatterView x:Name="topicsViewer"> <s:ScatterView.ItemTemplateSelector> <local:TopicViewerDataTemplateSelector> <DataTemplate DataType="{x:Type mvc:S7VideoTopic}"> <Grid> <ContentPresenter Content="{Binding MediaElement}" /> <s:SurfaceButton Visibility="{Binding MailToVisible}" x:Name="mailto" Tag="{Binding Titel}" Click="mailto_Click" HorizontalAlignment="Right" VerticalAlignment="Top" Background="Transparent" Width="62" Height="36"> <Image Source="/Resources/MailTo.png" /> </s:SurfaceButton> <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Center" Height="32"> <s:SurfaceButton Tag="{Binding MediaElement}" x:Name="btnPlay" Click="btnPlay_Click"> <Image Source="/Resources/control_play.png" /> </s:SurfaceButton> <s:SurfaceButton Tag="{Binding MediaElement}" x:Name="btnPause" Click="btnPause_Click"> <Image Source="/Resources/control_pause.png" /> </s:SurfaceButton> <s:SurfaceButton Tag="{Binding MediaElement}" x:Name="btnStop" Click="btnStop_Click"> <Image Source="/Resources/control_stop.png" /> </s:SurfaceButton> </StackPanel> </Grid> </DataTemplate> <DataTemplate DataType="{x:Type mvc:S7ImageTopic}"> <Grid> <ContentPresenter Content="{Binding Resource}" /> <s:SurfaceButton Visibility="{Binding MailToVisible}" x:Name="mailto" Tag="{Binding Titel}" Click="mailto_Click" HorizontalAlignment="Right" VerticalAlignment="Top" Background="Transparent" Width="62" Height="36"> <Image Source="/Resources/MailTo.png" /> </s:SurfaceButton> </Grid> </DataTemplate> <DataTemplate DataType="{x:Type local:Kassa}"> <ContentPresenter Content="{Binding}" Width="300" Height="355" /> </DataTemplate> </local:TopicViewerDataTemplateSelector> </s:ScatterView.ItemTemplateSelector> <s:ScatterView.ItemContainerStyle> <Style TargetType="s:ScatterViewItem"> <Setter Property="MinWidth" Value="200" /> <Setter Property="MinHeight" Value="150" /> <Setter Property="MaxWidth" Value="800" /> <Setter Property="MaxHeight" Value="700" /> <Setter Property="Width" Value="{Binding DefaultWidth}" /> <Setter Property="Height" Value="{Binding DefaultHeight}" /> <Setter Property="s:ScatterViewItem.CanMove" Value="{Binding CanMove}" /> <Setter Property="s:ScatterViewItem.CanScale" Value="{Binding CanScale}" /> <Setter Property="s:ScatterViewItem.CanRotate" Value="{Binding CanRotate}" /> <Setter Property="Background" Value="Transparent" /> </Style> </s:ScatterView.ItemContainerStyle> </s:ScatterView> Bart Roozendaal, Sevensteps

    Read the article

  • VoteCounts: bookmarklet to display up/down votes even for rep<1k

    - by SztupY
    Screenshot / Code Snippet About This small bookmarklet will allow anyone to use the "vulnerability" of the API that it allows you to check the up/down vote count - a feat you could normally achieve by being a 1k+rep user. Mainly useful for sites where you don't have this amount of rep, but want to check the stats of the more controversial questions (usually on meta) No API key is actually used here, but it's trivial to add one. License I don't think a code like this deserves anything other than WTFPL Download It's the following line (javascript - 375 bytes): javascript:(function(){a='jsonp';c=' .vote-count-post';d='up_vote_count';e='down_vote_count';$.ajax({url:document.location.href.replace(/(http:\/\/)(.*)(\/questions\/.*)\/.*/,'$1api.$2/1.0$3'),dataType:a,jsonp:a,success:function(x){b=x.questions[0];$('#question'+c).html(b[d]+"-"+b[e]);$.each(b.answers,function(z,y){$('#answer-'+y.answer_id+c).html(y[d]+"-"+y[e])})}})})() EDIT: This is longer, but it will make the result look like exactly on SO. Took a while to make it exactly 508 chars, so it works with IE too. javascript:(function(){w=function(t,q){l='_vote_count';h='up'+l;j='down'+l;k='</div>';s='<div style="color:';$(t).html(s+'green">'+(q[h]?'+':'')+q[h]+k+'<div class="vote-count-separator">'+k+s+'maroon">'+(q[j]==0?'':'-')+q[j]+k)};a='jsonp';c=' .vote-count-post';$.ajax({url:document.location.href.replace(/(http:\/\/)(.*)(\/questions\/.*)\/.*/,'$1api.$2/1.0$3'),dataType:a,jsonp:a,success:function(x){b=x.questions[0];w('#question'+c,b);$.each(b.answers,function(z,y){w('#answer-'+y.answer_id+c,y)})}})})() Platform For any jquery/bookmarklets compatible browser. Tested with Chrome, FF3.6 and IE8 for SU,SO,MSO Contact sztupy.hu Code It was written in notepad already in minified form. Used firebug to debug. Code is above. Contribute(=decrease code size or make the output nicer) any way you want. I'd be great if you'd do the second code shorter than 508 bytes. Known bugs If a question has more than 30 answers then some of the answers won't be resolved. This can be solved easily for <=100 answers, but for questions with more than 100 answers this is more difficult EDIT: updated to API version 1.0. Answers doesn't work yet.

    Read the article

  • CodePlex Daily Summary for Thursday, June 02, 2011

    CodePlex Daily Summary for Thursday, June 02, 2011Popular ReleasesDotRas: DotRas v1.2 (Version 1.2.4168): This release includes compiled (and signed) versions of the binaries, PDBs, CHM help documentation, along with both C# and VB.NET examples. Please don't forget to rate the release! If you find a bug, please open a work item and give as much description as possible. Stack traces, which operating system(s) you're targeting, and build type is also very helpful for bug hunting. If you find something you believe to be a bug but are not sure, create a new discussion on the discussions board. Thank...Caliburn Micro: WPF, Silverlight and WP7 made easy.: Caliburn.Micro v1.1 RTW: Download ContentsDebug and Release Assemblies Samples Changes.txt License.txt Release Highlights For WP7A new Tombstoning API based on ideas from Fluent NHibernate A new Launcher/Chooser API Strongly typed Navigation SimpleContainer included The full phone lifecycle is made easy to work with ie. we figure out whether your app is actually Resurrecting or just Continuing for you For WPFSupport for the Client Profile Better support for WinForms integration All PlatformsA power...Pssdiag and Sqldiag Manager: Diag Manager Release 10.5.1.202: This release fixed a bug regarding saving the final package. If you browse a folder when saving the configured package, the default file name will change back to pssd.exe. It should be pssd.cab.VidCoder: 0.9.1: Added color coding to the Log window. Errors are highlighted in red, HandBrake logs are in black and VidCoder logs are in dark blue. Moved enqueue button to the right with the other control buttons. Added logic to report failures when errors are logged during the encode or when the encode finishes prematurely. Added Copy button to Log window. Adjusted audio track selection box to always show the full track name. Changed encode job progress bar to also be colored yellow when the enco...Terraria Map Generator: TerrariaMapTool 1.0.0.3 Beta: 1) Catch all exception from the gui app. 2) Fixed the use of the graphics device to really use reach.AutoLoL: AutoLoL v2.0.1: - Fixed a small bug in Auto Login - Fixed the updaterEPPlus-Create advanced Excel 2007 spreadsheets on the server: EPPlus 2.9.0.1: EPPlus-Create advanced Excel 2007 spreadsheets on the server This version has been updated to .Net Framework 3.5 New Features Data Validation. PivotTables (Basic functionalliy...) Support for worksheet data sources. Column, Row, Page and Data fields. Date and Numeric grouping Build in styles. ...and more And some minor new features... Ranges Text-Property|Get the formated value AutofitColumns-method to set the column width from the content of the range LoadFromCollection-metho...jQuery ASP.Net MVC Controls: Version 1.4.0.0: Version 1.4.0.0 contains the following additions: Upgraded to MVC 3.0 Upgraded to jQuery 1.6.1 (Though the project supports all jQuery version from 1.4.x onwards) Upgraded to jqGrid 3.8 Better Razor View-Engine support Better Pager support, includes support for custom pagers Added jqGrid toolbar buttons support Search module refactored, with full suport for multiple filters and ordering And Code cleanup, bug-fixes and better controller configuration support.Restbucks on .Net: RestBucks Alpha 1: This is the first release of the application.Nearforums - ASP.NET MVC forum engine: Nearforums v6.0: Version 6.0 of Nearforums, the ASP.NET MVC Forum Engine, containing new features: Authentication using Membership Provider for SQL Server and MySql Spam prevention: Flood Control Moderation: Flag messages Content management: Pages: Create pages (about us/contact/texts) through web administration Allow nearforums to run as an IIS subapp Migrated Facebook Connect to OAuth 2.0 Visit the project Roadmap for more details.NetOffice - The easiest way to use Office in .NET: NetOffice Release 0.8b: Changes: - fix critical issue 15922(AccessViolationException) once and for all update is strongly recommended Includes: - Runtime Binaries and Source Code for .NET Framework:......v2.0, v3.0, v3.5, v4.0 - Tutorials in C# and VB.Net:..............................................................COM Proxy Management, Events, etc. - Examples in C# and VB.Net:............................................................Excel, Word, Outlook, PowerPoint, Access - COMAddin Examples in C# and VB....Facebook Graph Toolkit: Facebook Graph Toolkit 1.5.4186: Updates the API in response to Facebook's recent change of policy: All Graph Api accessing feeds or posts must provide a AccessToken.SharePoint Farm Poster: SharePoint Farm Poster: SharePoint Farm Poster is generated by a PowerShell Script. Run this script under the Farm Admin Account. After downloading, unblock the file in the Property Window. Current version is beta : v0.3.7Serviio for Windows Home Server: Beta Release 0.5.2.0: Ready for widespread beta. Synchronized build number to Serviio version to avoid confusion.AcDown????? - Anime&Comic Downloader: AcDown????? v3.0 Beta4: ??AcDown?????????????,??????????????,????、????。?????Acfun????? ????32??64? Windows XP/Vista/7 ????????????? ??:????????Windows XP???,?????????.NET Framework 2.0???(x86)?.NET Framework 2.0???(x64),?????"?????????"??? ??v3.0 Beta4 2011-5-31?? ???Bilibili.us????? ???? ?? ???"????" ???Bilibili.us??? ??????? ?? ??????? ?? ???????? ?? ?? ???Bilibili.us?????(??????????????????) ??????(6.cn)?????(????) ?? ?????Acfun?????????? ?????????????? ???QQ???????? ????????????Discussion...ClosedXML - The easy way to OpenXML: ClosedXML 0.53.2: New on this release: 1) Added FindCells, FindColumns, and FindRows methods to the workbook object. 2) Added cell.ValueCached property that holds Excel's cache of formula evaluations. 3) Added the following properties to the worksheets: ShowFormulas ShowGridLines ShowOutlineSymbols ShowRowColHeaders ShowRuler ShowWhiteSpace ShowZeros 4) Added methods Worksheets.Add(DataTable), Worksheets.Add(DataSet). See examples Adding DataTable as Worksheet, Adding DataSet 5) Fixed issues 6609,...CodeCopy Auto Code Converter: Code Copy v0.1: Full add-in, setup project source code and setup fileWordpress Theme 'Windows Metro': v1.00.0017: v1.00.0017 Dies ist eine Vorab-Version aus der Entwickler-Phase. This is a preview version from the development phase.Kooboo CMS: Kooboo CMS 3.02: Updated the Kooboo_CMS.zip at 2011-06-02 11:44 GMT 1.Fixed: Adding data rule issue on page. 2.Fixed: Caching issue for higher performance. Updated the Kooboo_CMS.zip at 2011-06-01 10:00 GMT 1. Fixed the published package throwed a compile error under WebSite mode. 2. Fixed the ContentHelper.NewMediaFolderObject return TextFolder issue. 3. Shorten the name of ContentHelper API. NewMediaFolderObject=>MediaFolder, NewTextFolderObject=> TextFolder, NewSchemaObject=>Schema. Also update the C...mojoPortal: 2.3.6.6: see release notes on mojoportal.com http://www.mojoportal.com/mojoportal-2366-released Note that we have separate deployment packages for .NET 3.5 and .NET 4.0 The deployment package downloads on this page are pre-compiled and ready for production deployment, they contain no C# source code. To download the source code see the Source Code Tab I recommend getting the latest source code using TortoiseHG, you can get the source code corresponding to this release here.New ProjectsAgile DDD Framework: Agile DDD FrameworkEnigma Suspicious Indicators Script: Enigma is a bash script that parses known suspicious indicators data from open and close source intelligence feeds and dynamiclly sends the data into ArcSight via CEF syslog. Please unzip the latest build and follow the instructions in the install.txt file.Fonqi ColorPicker for Umbraco: A Color Picker datatype for the Umbraco CMS.Fonqi.TemplatePicker Datatype for Umbraco: A template picker datatype for the umbraco cms. Implemented with the umbraco usercontrol wrapperGeneric Library: Still in building...Microsoft Surface StarterKit for VB.NET: Currently you can only create applications for Microsoft Surface in C #. Microsoft Surface Starterkit for VB.NET is an initial project of WPF that implements all the necessary references to create a Microsoft Surface application in Visual Basic. Actualmente solo se pueden crear aplicaciones para Microsoft Surface en C#. Microsoft Surface StarterKit for VB.NET es un proyecto inicial de WPF que implementa todas las referencias necesarias para crear una aplicación Microsoft Surface en Visual ...OpenCV Video Writer: For OpenCV2.2 Main Function: Use mouse to draw on window, edited video will be made in realtime. Support fading out effect and translucence drawing. This program use a read-edit-write model to achieve Realtime editing of video. Social Playlist: The Social Playlist Module is a DNN module that enables musicians to upload and manage their music online (possibly sale) and enables other users (not musician) to create personal playlist. The dynamics between musicians and user is similar to sites like MySpace and Ilike.splitbook: splitbookSQL Compact Query Analyzer: SQL Server Compact Edition Database Query AnalyzerTerm Store Migration Tool: Console application for migrating term store from one farm to another SharePoint farm. The tool exports the term store in an xml format which can be restored to same/another farm with same GUID's.TFS fa schifo: Questo progetto è da intendersi come dimostrazione del fatto che TFS fa veramente, inesorabilmente, indistintamente e veritatamente schifoTypheus Browser: A simple .Net browser based of the Typheus Browser from Homestuck.Ultimate Explorer: A Windows Explorer alternative.v76.DictionaryPicker for Umbraco: A Dictionary Picker Datatype for Umbraco CMS

    Read the article

  • SQL SERVER – Fix: Error: 8117: Operand data type bit is invalid for sum operator

    - by pinaldave
    Here is the very interesting error I received from a reader. He has very interesting question. He attempted to use BIT filed in the SUM aggregation function and he got following error. He went ahead with various different datatype (i.e. INT, TINYINT etc) and he was able to do the SUM but with BIT he faced the problem. Error Received: Msg 8117, Level 16, State 1, Line 1 Operand data type bit is invalid for sum operator. Reproduction of the error: Set up the environment USE tempdb GO -- Preparing Sample Data CREATE TABLE TestTable (ID INT, Flag BIT) GO INSERT INTO TestTable (ID, Flag) SELECT 1, 0 UNION ALL SELECT 2, 1 UNION ALL SELECT 3, 0 UNION ALL SELECT 4, 1 GO SELECT * FROM TestTable GO Following script will work fine: -- This will work fine SELECT SUM(ID) FROM TestTable GO However following generate error: -- This will generate error SELECT SUM(Flag) FROM TestTable GO The workaround is to convert or cast the BIT to INT: -- Workaround of error SELECT SUM(CONVERT(INT, Flag)) FROM TestTable GO Clean up the setup -- Clean up DROP TABLE TestTable GO Workaround: As mentioned in above script the workaround is to covert the bit datatype to another friendly data types like INT, TINYINT etc. 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

  • C++ Windows Forms application unhandled exception error when textbox empty

    - by cmorris1441
    I'm building a temperature conversion application in Visual Studio for a C++ course. It's a Windows Forms application and the code that I've written is below. There's other code to of course, but I'm not sure you need it to help me. My problem is, when I run the application if I don't have anything entered into either the txtFahrenheit or txtCelsius2 textboxes I get the following error: "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll" The application only works right now when a number is entered into both of the textboxes. I was told to try and use this: Double::TryParse() but I'm brand new to C++ and can't figure out how to use it, even after checking the MSDN library. Here's my code: private: System::Void btnFtoC_Click(System::Object^ sender, System::EventArgs^ e) { // Convert the input in the Fahrenheit textbox to a double datatype named fahrenheit for manipulation double fahrenheit = Convert::ToDouble(txtFahrenheit->Text); // Set the result string to F * (5/9) -32 double result = fahrenheit * .5556 - 32; // Set the Celsius text box to display the result string txtCelsius->Text = result.ToString(); } private: System::Void btnCtoF_Click(System::Object^ sender, System::EventArgs^ e) { // Convert the input in the Celsius textbox to a double datatype name celsius for manipulation double celsius = Convert::ToDouble(txtCelsius2->Text); // Set the result2 string to C * (9/5) + 32 double result2 = celsius * 1.8 + 32; // Set the Fahrenheit text box to display the result2 string txtFahrenheit2->Text = result2.ToString(); }

    Read the article

  • MVVM/WPF: DataTemplate is not changed in Wizard

    - by msfanboy
    Hello, I wonder why my contentcontrol(headeredcontentcontrol) does not change the datatemplates when I press the previous/next button. While debugging everything seems ok means I jump forth and back the collection of wizardpages but always the first page is shown and its header text not the usercontrol is visible. What do I have forgotten? using System; using System.Collections.Generic; using System.Linq; using System.Text; using GalaSoft.MvvmLight.Command; using System.Collections.ObjectModel; using System.Diagnostics; using System.ComponentModel; namespace TBM.ViewModel { public class WizardMainViewModel { WizardPageViewModelBase _currentPage; ReadOnlyCollection _pages; RelayCommand _moveNextCommand; RelayCommand _movePreviousCommand; public WizardMainViewModel() { this.CurrentPage = this.Pages[0]; } public RelayCommand MoveNextCommand { get { return _moveNextCommand ?? (_moveNextCommand = new RelayCommand(() => this.MoveToNextPage(), () => this.CanMoveToNextPage)); } } public RelayCommand MovePreviousCommand { get { return _movePreviousCommand ?? (_movePreviousCommand = new RelayCommand( () => this.MoveToPreviousPage(), () => this.CanMoveToPreviousPage)); } } bool CanMoveToPreviousPage { get { return 0 < this.CurrentPageIndex; } } bool CanMoveToNextPage { get { return this.CurrentPage != null && this.CurrentPage.IsValid(); } } void MoveToPreviousPage() { this.CurrentPage = this.Pages[this.CurrentPageIndex - 1]; } void MoveToNextPage() { if (this.CurrentPageIndex < this.Pages.Count - 1) this.CurrentPage = this.Pages[this.CurrentPageIndex + 1]; } /// <summary> /// Returns the page ViewModel that the user is currently viewing. /// </summary> public WizardPageViewModelBase CurrentPage { get { return _currentPage; } private set { if (value == _currentPage) return; if (_currentPage != null) _currentPage.IsCurrentPage = false; _currentPage = value; if (_currentPage != null) _currentPage.IsCurrentPage = true; this.OnPropertyChanged("CurrentPage"); this.OnPropertyChanged("IsOnLastPage"); } } public bool IsOnLastPage { get { return this.CurrentPageIndex == this.Pages.Count - 1; } } /// <summary> /// Returns a read-only collection of all page ViewModels. /// </summary> public ReadOnlyCollection<WizardPageViewModelBase> Pages { get { return _pages ?? CreatePages(); } } ReadOnlyCollection<WizardPageViewModelBase> CreatePages() { WizardPageViewModelBase welcomePage = new WizardWelcomePageViewModel(); WizardPageViewModelBase schoolclassPage = new WizardSchoolclassSubjectPageViewModel(); WizardPageViewModelBase lessonPage = new WizardLessonTimesPageViewModel(); WizardPageViewModelBase timetablePage = new WizardTimeTablePageViewModel(); WizardPageViewModelBase finishPage = new WizardFinishPageViewModel(); var pages = new List<WizardPageViewModelBase>(); pages.Add(welcomePage); pages.Add(schoolclassPage); pages.Add(lessonPage); pages.Add(timetablePage); pages.Add(finishPage); return _pages = new ReadOnlyCollection<WizardPageViewModelBase>(pages); } int CurrentPageIndex { get { if (this.CurrentPage == null) { Debug.Fail("Why is the current page null?"); return -1; } return this.Pages.IndexOf(this.CurrentPage); } } public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } } <UserControl x:Class="TBM.View.WizardMainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:ViewModel="clr-namespace:TBM.ViewModel" xmlns:View="clr-namespace:TBM.View" mc:Ignorable="d" > <UserControl.Resources> <DataTemplate DataType="{x:Type ViewModel:WizardWelcomePageViewModel}"> <View:WizardWelcomePageView /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:WizardSchoolclassSubjectPageViewModel}"> <View:WizardSchoolclassSubjectPageView /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:WizardLessonTimesPageViewModel}"> <View:WizardLessonTimesPageView /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:WizardTimeTablePageViewModel}"> <View:WizardTimeTablePageView /> </DataTemplate> <DataTemplate DataType="{x:Type ViewModel:WizardFinishPageViewModel}"> <View:WizardFinishPageView /> </DataTemplate> <!-- This Style inherits from the Button style seen above. --> <Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}" x:Key="moveNextButtonStyle"> <Setter Property="Content" Value="Next" /> <Style.Triggers> <DataTrigger Binding="{Binding Path=IsOnLastPage}" Value="True"> <Setter Property="Content" Value="Finish}" /> </DataTrigger> </Style.Triggers> </Style> <ViewModel:WizardMainViewModel x:Key="WizardMainViewModelID" /> </UserControl.Resources> <Grid DataContext="{Binding ., Source={StaticResource WizardMainViewModelID}}" > <Grid.RowDefinitions> <RowDefinition Height="310*" /> <RowDefinition Height="51*" /> </Grid.RowDefinitions> <!-- CONTENT --> <Grid Grid.Row="0" Background="LightGoldenrodYellow"> <HeaderedContentControl Content="{Binding CurrentPage}" Header="{Binding Path=CurrentPage.DisplayName}" /> </Grid> <!-- NAVIGATION BUTTONS --> <Grid Grid.Row="1" Background="Aquamarine"> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal"> <Button Command="{Binding MovePreviousCommand}" Content="Previous" /> <Button Command="{Binding MoveNextCommand}" Style="{StaticResource moveNextButtonStyle}" Content="Next" /> <Button Command="{Binding CancelCommand}" Content="Cancel" /> </StackPanel> </Grid> </Grid>

    Read the article

  • c# Counter requires 2 button clicks to update

    - by marko.ivanovski.nz
    Hi, I have a problem that has been bugging me all day. In my code I have the following: private int rowCount { get { return (int)ViewState["rowCount"]; } set { ViewState["rowCount"] = value; } } and a button event protected void addRow_Click(object sender, EventArgs e) { rowCount = rowCount + 1; } Then on Page_Load I read that value and create controls accordingly. I understand the button event fires AFTER the Page_Load fires so the value isn't updated until the next postback. Real nightmare. Here's the entire code: protected void Page_Load(object sender, EventArgs e) { string xmlValue = ""; //To read a value from a database if (xmlValue.Length > 0) { if (!Page.IsPostBack) { DataSet ds = XMLToDataSet(xmlValue); Table dimensionsTable = DataSetToTable(ds); tablePanel.Controls.Add(dimensionsTable); DataTable dt = ds.Tables["Dimensions"]; rowCount = dt.Rows.Count; colCount = dt.Columns.Count; } else { tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount))); } } else { if (!Page.IsPostBack) { rowCount = 2; colCount = 4; } tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount))); } } protected void submit_Click(object sender, EventArgs e) { resultsLabel.Text = Server.HtmlEncode(DataSetToStringXML(TableToDataSet((Table)tablePanel.Controls[0]))); } protected void addColumn_Click(object sender, EventArgs e) { colCount = colCount + 1; } protected void addRow_Click(object sender, EventArgs e) { rowCount = rowCount + 1; } public DataSet TableToDataSet(Table table) { DataSet ds = new DataSet(); DataTable dt = new DataTable("Dimensions"); ds.Tables.Add(dt); //Add headers for (int i = 0; i < table.Rows[0].Cells.Count; i++) { DataColumn col = new DataColumn(); TextBox headerTxtBox = (TextBox)table.Rows[0].Cells[i].Controls[0]; col.ColumnName = headerTxtBox.Text; col.Caption = headerTxtBox.Text; dt.Columns.Add(col); } for (int i = 0; i < table.Rows.Count; i++) { DataRow valueRow = dt.NewRow(); for (int x = 0; x < table.Rows[i].Cells.Count; x++) { TextBox valueTextBox = (TextBox)table.Rows[i].Cells[x].Controls[0]; valueRow[x] = valueTextBox.Text; } dt.Rows.Add(valueRow); } return ds; } public Table DataSetToTable(DataSet ds) { DataTable dt = ds.Tables["Dimensions"]; Table newTable = new Table(); //Add headers TableRow headerRow = new TableRow(); for (int i = 0; i < dt.Columns.Count; i++) { TableCell headerCell = new TableCell(); TextBox headerTxtBox = new TextBox(); headerTxtBox.ID = "HeadersTxtBox" + i.ToString(); headerTxtBox.Font.Bold = true; headerTxtBox.Text = dt.Columns[i].ColumnName; headerCell.Controls.Add(headerTxtBox); headerRow.Cells.Add(headerCell); } newTable.Rows.Add(headerRow); //Add value rows for (int i = 0; i < dt.Rows.Count; i++) { TableRow valueRow = new TableRow(); for (int x = 0; x < dt.Columns.Count; x++) { TableCell valueCell = new TableCell(); TextBox valueTxtBox = new TextBox(); valueTxtBox.ID = "ValueTxtBox" + i.ToString() + i + x + x.ToString(); valueTxtBox.Text = dt.Rows[i][x].ToString(); valueCell.Controls.Add(valueTxtBox); valueRow.Cells.Add(valueCell); } newTable.Rows.Add(valueRow); } return newTable; } public DataSet DefaultDataSet(int rows, int cols) { DataSet ds = new DataSet(); DataTable dt = new DataTable("Dimensions"); ds.Tables.Add(dt); DataColumn nameCol = new DataColumn(); nameCol.Caption = "Name"; nameCol.ColumnName = "Name"; nameCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(nameCol); DataColumn widthCol = new DataColumn(); widthCol.Caption = "Width"; widthCol.ColumnName = "Width"; widthCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(widthCol); if (cols > 2) { DataColumn heightCol = new DataColumn(); heightCol.Caption = "Height"; heightCol.ColumnName = "Height"; heightCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(heightCol); } if (cols > 3) { DataColumn depthCol = new DataColumn(); depthCol.Caption = "Depth"; depthCol.ColumnName = "Depth"; depthCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(depthCol); } if (cols > 4) { int newColCount = cols - 4; for (int i = 0; i < newColCount; i++) { DataColumn newCol = new DataColumn(); newCol.Caption = "New " + i.ToString(); newCol.ColumnName = "New " + i.ToString(); newCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(newCol); } } for (int i = 0; i < rows; i++) { DataRow newRow = dt.NewRow(); newRow["Name"] = "Name " + i.ToString(); newRow["Width"] = "Width " + i.ToString(); if (cols > 2) { newRow["Height"] = "Height " + i.ToString(); } if (cols > 3) { newRow["Depth"] = "Depth " + i.ToString(); } dt.Rows.Add(newRow); } return ds; } public DataSet XMLToDataSet(string xml) { StringReader sr = new StringReader(xml); DataSet ds = new DataSet(); ds.ReadXml(sr); return ds; } public string DataSetToStringXML(DataSet ds) { XmlDocument _XMLDoc = new XmlDocument(); _XMLDoc.LoadXml(ds.GetXml()); StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); XmlDocument xml = _XMLDoc; xml.WriteTo(xw); return sw.ToString(); } private int rowCount { get { return (int)ViewState["rowCount"]; } set { ViewState["rowCount"] = value; } } private int colCount { get { return (int)ViewState["colCount"]; } set { ViewState["colCount"] = value; } } Thanks in advance, Marko

    Read the article

  • Creating packages in code – Execute SQL Task

    The Execute SQL Task is for obvious reasons very well used, so I thought if you are building packages in code the chances are you will be using it. Using the task basic features of the task are quite straightforward, add the task and set some properties, just like any other. When you start interacting with variables though it can be a little harder to grasp so these samples should see you through. Some of these more advanced features are explained in much more detail in our ever popular post The Execute SQL Task, here I’ll just be showing you how to implement them in code. The abbreviated code blocks below demonstrate the different features of the task. The complete code has been encapsulated into a sample class which you can download (ExecSqlPackage.cs). Each feature described has its own method in the sample class which is mentioned after the code block. This first sample just shows adding the task, setting the basic properties for a connection and of course an SQL statement. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Set required properties taskHost.Properties["Connection"].SetValue(taskHost, sqlConnection.ID); taskHost.Properties["SqlStatementSource"].SetValue(taskHost, "SELECT * FROM sysobjects"); For the full version of this code, see the CreatePackage method in the sample class. The AddSqlConnection method is a helper method that adds an OLE-DB connection to the package, it is of course in the sample class file too. Returning a single value with a Result Set The following sample takes a different approach, getting a reference to the ExecuteSQLTask object task itself, rather than just using the non-specific TaskHost as above. Whilst it means we need to add an extra reference to our project (Microsoft.SqlServer.SQLTask) it makes coding much easier as we have compile time validation of any property and types we use. For the more complex properties that is very valuable and saves a lot of time during development. The query has also been changed to return a single value, one row and one column. The sample shows how we can return that value into a variable, which we also add to our package in the code. To do this manually you would set the Result Set property on the General page to Single Row and map the variable on the Result Set page in the editor. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Add variable to hold result value package.Variables.Add("Variable", false, "User", 0); // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'"; // Set single row result set task.ResultSetType = ResultSetType.ResultSetType_SingleRow; // Add result set binding, map the id column to variable task.ResultSetBindings.Add(); IDTSResultBinding resultBinding = task.ResultSetBindings.GetBinding(0); resultBinding.ResultName = "id"; resultBinding.DtsVariableName = "User::Variable"; For the full version of this code, see the CreatePackageResultVariable method in the sample class. The other types of Result Set behaviour are just a variation on this theme, set the property and map the result binding as required. Parameter Mapping for SQL Statements This final example uses a parameterised SQL statement, with the coming from a variable. The syntax varies slightly between connection types, as explained in the Working with Parameters and Return Codes in the Execute SQL Taskhelp topic, but OLE-DB is the most commonly used, for which a question mark is the parameter value placeholder. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, ".", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = ?"; // Add variable to hold parameter value package.Variables.Add("Variable", false, "User", "sysrowsets"); // Add input parameter binding task.ParameterBindings.Add(); IDTSParameterBinding parameterBinding = task.ParameterBindings.GetBinding(0); parameterBinding.DtsVariableName = "User::Variable"; parameterBinding.ParameterDirection = ParameterDirections.Input; parameterBinding.DataType = (int)OleDBDataTypes.VARCHAR; parameterBinding.ParameterName = "0"; parameterBinding.ParameterSize = 255; For the full version of this code, see the CreatePackageParameterVariable method in the sample class. You’ll notice the data type has to be specified for the parameter IDTSParameterBinding .DataType Property, and these type codes are connection specific too. My enumeration I wrote several years ago is shown below was probably done by reverse engineering a package and also the API header file, but I recently found a very handy post that covers more connections as well for exactly this, Setting the DataType of IDTSParameterBinding objects (Execute SQL Task). /// <summary> /// Enumeration of OLE-DB types, used when mapping OLE-DB parameters. /// </summary> private enum OleDBDataTypes { BYTE = 0x11, CURRENCY = 6, DATE = 7, DB_VARNUMERIC = 0x8b, DBDATE = 0x85, DBTIME = 0x86, DBTIMESTAMP = 0x87, DECIMAL = 14, DOUBLE = 5, FILETIME = 0x40, FLOAT = 4, GUID = 0x48, LARGE_INTEGER = 20, LONG = 3, NULL = 1, NUMERIC = 0x83, NVARCHAR = 130, SHORT = 2, SIGNEDCHAR = 0x10, ULARGE_INTEGER = 0x15, ULONG = 0x13, USHORT = 0x12, VARCHAR = 0x81, VARIANT_BOOL = 11 } Download Sample code ExecSqlPackage.cs (10KB)

    Read the article

  • Creating packages in code – Execute SQL Task

    The Execute SQL Task is for obvious reasons very well used, so I thought if you are building packages in code the chances are you will be using it. Using the task basic features of the task are quite straightforward, add the task and set some properties, just like any other. When you start interacting with variables though it can be a little harder to grasp so these samples should see you through. Some of these more advanced features are explained in much more detail in our ever popular post The Execute SQL Task, here I’ll just be showing you how to implement them in code. The abbreviated code blocks below demonstrate the different features of the task. The complete code has been encapsulated into a sample class which you can download (ExecSqlPackage.cs). Each feature described has its own method in the sample class which is mentioned after the code block. This first sample just shows adding the task, setting the basic properties for a connection and of course an SQL statement. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Set required properties taskHost.Properties["Connection"].SetValue(taskHost, sqlConnection.ID); taskHost.Properties["SqlStatementSource"].SetValue(taskHost, "SELECT * FROM sysobjects"); For the full version of this code, see the CreatePackage method in the sample class. The AddSqlConnection method is a helper method that adds an OLE-DB connection to the package, it is of course in the sample class file too. Returning a single value with a Result Set The following sample takes a different approach, getting a reference to the ExecuteSQLTask object task itself, rather than just using the non-specific TaskHost as above. Whilst it means we need to add an extra reference to our project (Microsoft.SqlServer.SQLTask) it makes coding much easier as we have compile time validation of any property and types we use. For the more complex properties that is very valuable and saves a lot of time during development. The query has also been changed to return a single value, one row and one column. The sample shows how we can return that value into a variable, which we also add to our package in the code. To do this manually you would set the Result Set property on the General page to Single Row and map the variable on the Result Set page in the editor. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Add variable to hold result value package.Variables.Add("Variable", false, "User", 0); // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'"; // Set single row result set task.ResultSetType = ResultSetType.ResultSetType_SingleRow; // Add result set binding, map the id column to variable task.ResultSetBindings.Add(); IDTSResultBinding resultBinding = task.ResultSetBindings.GetBinding(0); resultBinding.ResultName = "id"; resultBinding.DtsVariableName = "User::Variable"; For the full version of this code, see the CreatePackageResultVariable method in the sample class. The other types of Result Set behaviour are just a variation on this theme, set the property and map the result binding as required. Parameter Mapping for SQL Statements This final example uses a parameterised SQL statement, with the coming from a variable. The syntax varies slightly between connection types, as explained in the Working with Parameters and Return Codes in the Execute SQL Taskhelp topic, but OLE-DB is the most commonly used, for which a question mark is the parameter value placeholder. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, ".", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = ?"; // Add variable to hold parameter value package.Variables.Add("Variable", false, "User", "sysrowsets"); // Add input parameter binding task.ParameterBindings.Add(); IDTSParameterBinding parameterBinding = task.ParameterBindings.GetBinding(0); parameterBinding.DtsVariableName = "User::Variable"; parameterBinding.ParameterDirection = ParameterDirections.Input; parameterBinding.DataType = (int)OleDBDataTypes.VARCHAR; parameterBinding.ParameterName = "0"; parameterBinding.ParameterSize = 255; For the full version of this code, see the CreatePackageParameterVariable method in the sample class. You’ll notice the data type has to be specified for the parameter IDTSParameterBinding .DataType Property, and these type codes are connection specific too. My enumeration I wrote several years ago is shown below was probably done by reverse engineering a package and also the API header file, but I recently found a very handy post that covers more connections as well for exactly this, Setting the DataType of IDTSParameterBinding objects (Execute SQL Task). /// <summary> /// Enumeration of OLE-DB types, used when mapping OLE-DB parameters. /// </summary> private enum OleDBDataTypes { BYTE = 0x11, CURRENCY = 6, DATE = 7, DB_VARNUMERIC = 0x8b, DBDATE = 0x85, DBTIME = 0x86, DBTIMESTAMP = 0x87, DECIMAL = 14, DOUBLE = 5, FILETIME = 0x40, FLOAT = 4, GUID = 0x48, LARGE_INTEGER = 20, LONG = 3, NULL = 1, NUMERIC = 0x83, NVARCHAR = 130, SHORT = 2, SIGNEDCHAR = 0x10, ULARGE_INTEGER = 0x15, ULONG = 0x13, USHORT = 0x12, VARCHAR = 0x81, VARIANT_BOOL = 11 } Download Sample code ExecSqlPackage.cs (10KB)

    Read the article

  • SQL SERVER – SmallDateTime and Precision – A Continuous Confusion

    - by pinaldave
    Some kinds of confusion never go away. Here is one of the ancient confusing things in SQL. The precision of the SmallDateTime is one concept that confuses a lot of people, proven by the many messages I receive everyday relating to this subject. Let me start with the question: What is the precision of the SMALLDATETIME datatypes? What is your answer? Write it down on your notepad. Now if you do not want to continue reading the blog post, head to my previous blog post over here: SQL SERVER – Precision of SMALLDATETIME. A Social Media Question Since the increase of social media conversations, I noticed that the amount of the comments I receive on this blog is a bit staggering. I receive lots of questions on facebook, twitter or Google+. One of the very interesting questions yesterday was asked on Facebook by Raghavendra. I am re-organizing his script and asking all of the questions he has asked me. Let us see if we could help him with his question: CREATE TABLE #temp (name VARCHAR(100),registered smalldatetime) GO DECLARE @test smalldatetime SET @test=GETDATE() INSERT INTO #temp VALUES ('Value1',@test) INSERT INTO #temp VALUES ('Value2',@test) GO SELECT * FROM #temp ORDER BY registered DESC GO DROP TABLE #temp GO Now when the above script is ran, we will get the following result: Well, the expectation of the query was to have the following result. The row which was inserted last was expected to return as first row in result set as the ORDER BY descending. Side note: Because the requirement is to get the latest data, we can’t use any  column other than smalldatetime column in order by. If we use name column in the order by, we will get an incorrect result as it can be any name. My Initial Reaction My initial reaction was as follows: 1) DataType DateTime2: If file precision of the column is expected from the column which store date and time, it should not be smalldatetime. The precision of the column smalldatetime is One Minute (Read Here) for finer precision use DateTime or DateTime2 data type. Here is the code which includes above suggestion: CREATE TABLE #temp (name VARCHAR(100), registered datetime2) GO DECLARE @test datetime2 SET @test=GETDATE() INSERT INTO #temp VALUES ('Value1',@test) INSERT INTO #temp VALUES ('Value2',@test) GO SELECT * FROM #temp ORDER BY registered DESC GO DROP TABLE #temp GO 2) Tie Breaker Identity: There are always possibilities that two rows were inserted at the same time. In that case, you may need a tie breaker. If you have an increasing identity column, you can use that as a tie breaker as well. CREATE TABLE #temp (ID INT IDENTITY(1,1), name VARCHAR(100),registered datetime2) GO DECLARE @test datetime2 SET @test=GETDATE() INSERT INTO #temp VALUES ('Value1',@test) INSERT INTO #temp VALUES ('Value2',@test) GO SELECT * FROM #temp ORDER BY ID DESC GO DROP TABLE #temp GO Those two were the quick suggestions I provided. It is not necessary that you should use both advices. It is possible that one can use only DATETIME datatype or Identity column can have datatype of BIGINT or have another tie breaker. An Alternate NO Solution In the facebook thread this was also discussed as one of the solutions: CREATE TABLE #temp (name VARCHAR(100),registered smalldatetime) GO DECLARE @test smalldatetime SET @test=GETDATE() INSERT INTO #temp VALUES ('Value1',@test) INSERT INTO #temp VALUES ('Value2',@test) GO SELECT name, registered, ROW_NUMBER() OVER(ORDER BY registered DESC) AS "Row Number" FROM #temp ORDER BY 3 DESC GO DROP TABLE #temp GO However, I believe it is not the solution and can be further misleading if used in a production server. Here is the example of why it is not a good solution: CREATE TABLE #temp (name VARCHAR(100) NOT NULL,registered smalldatetime) GO DECLARE @test smalldatetime SET @test=GETDATE() INSERT INTO #temp VALUES ('Value1',@test) INSERT INTO #temp VALUES ('Value2',@test) GO -- Before Index SELECT name, registered, ROW_NUMBER() OVER(ORDER BY registered DESC) AS "Row Number" FROM #temp ORDER BY 3 DESC GO -- Create Index ALTER TABLE #temp ADD CONSTRAINT [PK_#temp] PRIMARY KEY CLUSTERED (name DESC) GO -- After Index SELECT name, registered, ROW_NUMBER() OVER(ORDER BY registered DESC) AS "Row Number" FROM #temp ORDER BY 3 DESC GO DROP TABLE #temp GO Now let us examine the resultset. You will notice that an index which is created on the base table which is (indeed) schema change the table but can affect the resultset. As you can see, an index can change the resultset, so this method is not yet perfect to get the latest inserted resultset. No Schema Change Requirement After giving these two suggestions, I was waiting for the feedback of the asker. However, the requirement of the asker was there can’t be any schema change because the application was used by many other applications. I validated again, and of course, the requirement is no schema change at all. No addition of the column of change of datatypes of any other columns. There is no further help as well. This is indeed an interesting question. I personally can’t think of any solution which I could provide him given the requirement of no schema change. Can you think of any other solution to this? Need of Database Designer This question once again brings up another ancient question:  “Do we need a database designer?” I often come across databases which are facing major performance problems or have redundant data. Normalization is often ignored when a database is built fast under a very tight deadline. Often I come across a database which has table with unnecessary columns and performance problems. While working as Developer Lead in my earlier jobs, I have seen developers adding columns to tables without anybody’s consent and retrieving them as SELECT *.  There is a lot to discuss on this subject in detail, but for now, let’s discuss the question first. Do you have any suggestions for the above question? Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: CodeProject, Developer Training, PostADay, SQL, SQL Authority, SQL DateTime, SQL Query, SQL Server, SQL Tips and Tricks, SQLServer, T SQL, Technology

    Read the article

  • IsNumeric() Broken? Only up to a point.

    - by Phil Factor
    In SQL Server, probably the best-known 'broken' function is poor ISNUMERIC() . The documentation says 'ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0. ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($).'Although it will take numeric data types (No, I don't understand why either), its main use is supposed to be to test strings to make sure that you can convert them to whatever numeric datatype you are using (int, numeric, bigint, money, smallint, smallmoney, tinyint, float, decimal, or real). It wouldn't actually be of much use anyway, since each datatype has different rules. You actually need a RegEx to do a reasonably safe check. The other snag is that the IsNumeric() function  is a bit broken. SELECT ISNUMERIC(',')This cheerfully returns 1, since it believes that a comma is a currency symbol (not a thousands-separator) and you meant to say 0, in this strange currency.  However, SELECT ISNUMERIC(N'£')isn't recognized as currency.  '+' and  '-' is seen to be numeric, which is stretching it a bit. You'll see that what it allows isn't really broken except that it doesn't recognize Unicode currency symbols: It just tells you that one numeric type is likely to accept the string if you do an explicit conversion to it using the string. Both these work fine, so poor IsNumeric has to follow suit. SELECT  CAST('0E0' AS FLOAT)SELECT  CAST (',' AS MONEY) but it is harder to predict which data type will accept a '+' sign. SELECT  CAST ('+' AS money) --0.00SELECT  CAST ('+' AS INT)   --0SELECT  CAST ('+' AS numeric)/* Msg 8115, Level 16, State 6, Line 4 Arithmetic overflow error converting varchar to data type numeric.*/SELECT  CAST ('+' AS FLOAT)/*Msg 8114, Level 16, State 5, Line 5Error converting data type varchar to float.*/> So we can begin to say that the maybe IsNumeric isn't really broken, but is answering a silly question 'Is there some numeric datatype to which i can convert this string? Almost, but not quite. The bug is that it doesn't understand Unicode currency characters such as the euro or franc which are actually valid when used in the CAST function. (perhaps they're delaying fixing the euro bug just in case it isn't necessary).SELECT ISNUMERIC (N'?23.67') --0SELECT  CAST (N'?23.67' AS money) --23.67SELECT ISNUMERIC (N'£100.20') --1SELECT  CAST (N'£100.20' AS money) --100.20 Also the CAST function itself is quirky in that it cannot convert perfectly reasonable string-representations of integers into integersSELECT ISNUMERIC('200,000')       --1SELECT  CAST ('200,000' AS INT)   --0/*Msg 245, Level 16, State 1, Line 2Conversion failed when converting the varchar value '200,000' to data type int.*/  A more sensible question is 'Is this an integer or decimal number'. This cuts out a lot of the apparent quirkiness. We do this by the '+E0' trick. If we want to include floats in the check, we'll need to make it a bit more complicated. Here is a small test-rig. SELECT  PossibleNumber,         ISNUMERIC(CAST(PossibleNumber AS NVARCHAR(20)) + 'E+00') AS Hack,        ISNUMERIC (PossibleNumber + CASE WHEN PossibleNumber LIKE '%E%'                                          THEN '' ELSE 'E+00' END) AS Hackier,        ISNUMERIC(PossibleNumber) AS RawIsNumericFROM    (SELECT CAST(',' AS NVARCHAR(10)) AS PossibleNumber          UNION SELECT '£' UNION SELECT '.'         UNION SELECT '56' UNION SELECT '456.67890'         UNION SELECT '0E0' UNION SELECT '-'         UNION SELECT '-' UNION SELECT '.'         UNION  SELECT N'?' UNION SELECT N'¢'        UNION  SELECT N'?' UNION SELECT N'?34.56'         UNION SELECT '-345' UNION SELECT '3.332228E+09') AS examples Which gives the result ... PossibleNumber Hack Hackier RawIsNumeric-------------- ----------- ----------- ------------? 0 0 0- 0 0 1, 0 0 1. 0 0 1¢ 0 0 1£ 0 0 1? 0 0 0?34.56 0 0 00E0 0 1 13.332228E+09 0 1 1-345 1 1 1456.67890 1 1 156 1 1 1 I suspect that this is as far as you'll get before you abandon IsNumeric in favour of a regex. You can only get part of the way with the LIKE wildcards, because you cannot specify quantifiers. You'll need full-blown Regex strings like these ..[-+]?\b[0-9]+(\.[0-9]+)?\b #INT or REAL[-+]?\b[0-9]{1,3}\b #TINYINT[-+]?\b[0-9]{1,5}\b #SMALLINT.. but you'll get even these to fail to catch numbers out of range.So is IsNumeric() an out and out rogue function? Not really, I'd say, but then it would need a damned good lawyer.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >