Search Results

Search found 6651 results on 267 pages for 'description'.

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

  • Django: how to cleanup form fields and avoid code duplication

    - by Alexander Konstantinov
    Quite often I need to filter some form data before using it (saving to database etc.) Let's say I want to strip whitespaces and replace repeating whitespaces with a single one in most of the text fields, in many forms. It's not difficult to do this using clean_<fieldname> methods: # Simplified model with two text fields class MyModel(models.Model): title = models.CharField() description = models.CharField() # Model-based form class MyForm(forms.ModelForm): class Meta: model = MyModel def clean_title(self): title = self.cleaned_data['title'] return re.sub(r'\s{2,}', ' ', title.strip()) def clean_description(self): description = self.cleaned_data['description'] return re.sub(r'\s{2,}', ' ', description.strip()) It does exactly what I need, and has a nice side effect which I like: if user enters only whitespaces, the field will be considered empty and therefore invalid (if it is required) and I don't even have to throw a ValidationError. The obvious problem here is code duplication. Even if I'll create some function for that, say my_text_filter, I'll have to call it for every text field in all my forms: from myproject.filters import my_text_filter class MyForm(forms.ModelForm): class Meta: model = MyModel def clean_title(self): return my_text_filter(self.cleaned_data['title']) def clean_description(self): return my_text_filter(self.cleaned_data['description']) The question: is there any standard and simple way in Django (I use version 1.2 if that matters) to do this (like, for example, by adding property validators = {'title': my_text_filter, 'description': my_text_filter} to MyModel), or at least some more or less standard workaround? I've read about form validation and validators in the documentation, but couldn't find what I need there.

    Read the article

  • Horrorble performance using ListViews with nested objects in WPF

    - by Christian
    Hi community, like mentioned in the title I get a horrible performance if I use ListViews with nested objects. My scenario is: Each row of a ListView presents an object of the class Transaction with following attributes: private int mTransactionID; private IBTTransactionSender mSender; private IBTTransactionReceiver mReceiver; private BTSubstrate mSubstrate; private double mAmount; private string mDeliveryNote; private string mNote; private DateTime mTransactionDate; private DateTime mCreationTimestamp; private BTEmployee mEmployee; private bool mImported; private bool mDescendedFromRecurringTransaction; Each attribute can be accessed by its corresponding property. An ObservableCollection<Transaction> is bound to the ItemsSource of a ListView. The ListView itself looks like the following: </ListView.GroupStyle> <ListView.View> <GridView> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.ToSave" Width="80"> <GridViewColumnHeader Name="GVCHLoadedToSave" Style="{StaticResource ListViewHeaderStyle}">Speichern</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <CheckBox Name="CBListViewItem" IsChecked="{Binding Path=Transaction.ToSave, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.TransactionDate" Width="80"> <GridViewColumnHeader Name="GVCHLoadedDate" Style="{StaticResource ListViewHeaderStyle}">Datum</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding ElementName=DPDate, Path=Text}" Style="{StaticResource GridBlockStyle}"/> <toolkit:DatePicker Name="DPDate" Width="{Binding ElementName=GVCHDate, Path=ActualWidth}" SelectedDateFormat="Short" Style="{StaticResource GridEditStyle}" SelectedDate="{Binding Path=Transaction.TransactionDate, Mode=TwoWay}" SelectedDateChanged="DPDate_SelectedDateChanged"/> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Sender.Description" Width="120"> <GridViewColumnHeader Name="GVCHLoadedSender" Style="{StaticResource ListViewHeaderStyle}">Von</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Sender.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBSender" Width="{Binding ElementName=GVCHSender, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Sender}" DisplayMemberPath="Description" Text="{Binding Path=Sender.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=SenderList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Receiver.Description" Width="120"> <GridViewColumnHeader Name="GVCHLoadedReceiver" Style="{StaticResource ListViewHeaderStyle}">Nach</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Receiver.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBReceiver" Width="{Binding ElementName=GVCHReceiver, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Receiver}" DisplayMemberPath="Description" Text="{Binding Path=Receiver.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=ReceiverList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Substrate.Description" Width="140"> <GridViewColumnHeader Name="GVCHLoadedSubstrate" Style="{StaticResource ListViewHeaderStyle}">Substrat</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Substrate.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBSubstrate" Width="{Binding ElementName=GVCHSubstrate, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Substrate}" DisplayMemberPath="Description" Text="{Binding Path=Substrate.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=SubstrateList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Amount" Width="80"> <GridViewColumnHeader Name="GVCHLoadedAmount" Style="{StaticResource ListViewHeaderStyle}">Menge [kg]</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Amount}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBAmount" Text="{Binding Path=Transaction.Amount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHAmount, Path=ActualWidth}" Style="{StaticResource GridTextBoxStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.DeliveryNote" Width="100"> <GridViewColumnHeader Name="GVCHLoadedDeliveryNote" Style="{StaticResource ListViewHeaderStyle}">Lieferschein Nr.</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.DeliveryNote}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBDeliveryNote" Text="{Binding Path=Transaction.DeliveryNote, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHDeliveryNote, Path=ActualWidth}" Style="{StaticResource GridEditStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Note" Width="190"> <GridViewColumnHeader Name="GVCHLoadedNote" Style="{StaticResource ListViewHeaderStyle}">Bemerkung</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Note}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBNote" Text="{Binding Path=Transaction.Note, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHNote, Path=ActualWidth}" Style="{StaticResource GridEditStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Employee.LastName" Width="100"> <GridViewColumnHeader Name="GVCHLoadedEmployee" Style="{StaticResource ListViewHeaderStyle}">Mitarbeiter</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Employee.LastName}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBEmployee" Width="{Binding ElementName=GVCHEmployee, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Employee}" DisplayMemberPath="LastName" Text="{Binding Path=Employee.LastName, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=EmployeeList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> As you can see in the screenshot the user got the possibility to change the values of the transaction attributes with comboboxes. Ok now to my problem. If I click on the "Laden" button the application will load about 150 entries in the ObservableCollection<Transaction>. Before I fill the collection I set the ItemsSource of the ListView to null and after filling I bind the collection to the ItemsSource once again. The loading itself takes a few milliseconds, but the rendering of the filled collection takes a long time (150 entries = about 20 sec). I tested to delete all Comboboxes out of the xaml and i got a better performance, because I don't have to fill the ComboBoxes for each row. But I need to have these comboboxes for modifing the attributes of the Transaction. Does anybody know how to improve the performance? THX

    Read the article

  • Rss Feed Java MVC

    - by GigaPr
    Hi, i would like to create some RSS Feeds for my website. I managed to crate the XML file but How do i display it in a nice format like http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml and how do i crate the little icon in the url box? by the way my XML file looks like <?xml version='1.0' encoding='UTF-8'?> <rss version="2.0"> <channel> <title>title</title> <description>desciption</description> <link>LINK</link> <dateCreated>2010-05-31 00:00:00.0</dateCreated> <language>Italian</language> <item> <title>pojpoj</title> <description>pojpojpoj</description> <link>ojpojpoj</link> <dateCreated>2010-06-03 00:00:00.0</dateCreated> <pubDate>2010-06-03 00:00:00.0</pubDate> </item> <item> <title>dfojp</title> <description>pojpojpoj</description> <link>pojpoj</link> <dateCreated>2010-06-03 00:00:00.0</dateCreated> <pubDate>2010-06-03 00:00:00.0</pubDate> </item> </channel> </rss> Thanks

    Read the article

  • Evaluate or Show HTML using Javascript

    - by Anita
    Hello, I have this...portion of code in Javascript: var description = document.createElement('P'); description.className='rssBoxDescription'; description.innerHTML = itemTokens[2]; div.appendChild(description); I see that description gets the HTML value and displays as plain HTML coding not as HTML processing it shouldbe ... how to convert this HTML value in description to be appended to div element shown as HTML...which is not showing. Also it has value something like: <table><tr><td style="padding: 0 5px"><ahref="xttp://picasaweb.google.com/linktoimagepage"><imgtag style="border:1px solid #5C7FB9" s_rc="xttp://lh3.ggpht.com/imagepath" alt="image.jpg"/></a></td><td valign="top"><font color="#6B6B6B">Date: </font><font color="#333333">Jun 28, 2007 9:00 AM</font><br/><font color=\"#6B6B6B\">Number of Comments on Photo:</font><font color=\"#333333\">0</font><br/><p><ahref="xttp://picasaweb.google.com/linktoimage"><font color="#3964C2">View Photo</font></a></p></td></tr></table> Pls help Anita

    Read the article

  • c++ queue template

    - by Dalton Conley
    ALright, pardon my messy code please. Below is my queue class. #include <iostream> using namespace std; #ifndef QUEUE #define QUEUE /*---------------------------------------------------------------------------- Student Class # Methods # Student() // default constructor Student(string, int) // constructor display() // out puts a student # Data Members # Name // string name Id // int id ----------------------------------------------------------------------------*/ class Student { public: Student() { } Student(string iname, int iid) { name = iname; id = iid; } void display(ostream &out) const { out << "Student Name: " << name << "\tStudent Id: " << id << "\tAddress: " << this << endl; } private: string name; int id; }; // define a typedef of a pointer to a student. typedef Student * StudentPointer; template <typename T> class Queue { public: /*------------------------------------------------------------------------ Queue Default Constructor Preconditions: none Postconditions: assigns default values for front and back to 0 description: constructs a default empty Queue. ------------------------------------------------------------------------*/ Queue() : myFront(0), myBack(0) {} /*------------------------------------------------------------------------ Copy Constructor Preconditions: requres a reference to a value for which you are copying Postconditions: assigns a copy to the parent Queue. description: Copys a queue and assigns it to the parent Queue. ------------------------------------------------------------------------*/ Queue(const T & q) { myFront = myBack = 0; if(!q.empty()) { // copy the first node myFront = myBack = new Node(q.front()); NodePointer qPtr = q.myFront->next; while(qPtr != NULL) { myBack->next = new Node(qPtr->data); myBack = myBack->next; qPtr = qPtr->next; } } } /*------------------------------------------------------------------------ Destructor Preconditions: none Postconditions: deallocates the dynamic memory for the Queue description: deletes the memory stored for a Queue. ------------------------------------------------------------------------*/ ~Queue() { NodePointer prev = myFront, ptr; while(prev != NULL) { ptr = prev->next; delete prev; prev = ptr; } } /*------------------------------------------------------------------------ Empty() Preconditions: none Postconditions: returns a boolean value. description: returns true/false based on if the queue is empty or full. ------------------------------------------------------------------------*/ bool empty() const { return (myFront == NULL); } /*------------------------------------------------------------------------ Enqueue Preconditions: requires a constant reference Postconditions: allocates memory and appends a value at the end of a queue description: ------------------------------------------------------------------------*/ void enqueue(const T & value) { NodePointer newNodePtr = new Node(value); if(empty()) { myFront = myBack = newNodePtr; newNodePtr->next = NULL; } else { myBack->next = newNodePtr; myBack = newNodePtr; newNodePtr->next = NULL; } } /*------------------------------------------------------------------------ Display Preconditions: requires a reference of type ostream Postconditions: returns the ostream value (for chaining) description: outputs the contents of a queue. ------------------------------------------------------------------------*/ void display(ostream & out) const { NodePointer ptr; ptr = myFront; while(ptr != NULL) { out << ptr->data << " "; ptr = ptr->next; } out << endl; } /*------------------------------------------------------------------------ Front Preconditions: none Postconditions: returns a value of type T description: returns the first value in the parent Queue. ------------------------------------------------------------------------*/ T front() const { if ( !empty() ) return (myFront->data); else { cerr << "*** Queue is empty -- returning garbage value ***\n"; T * temp = new(T); T garbage = * temp; delete temp; return garbage; } } /*------------------------------------------------------------------------ Dequeue Preconditions: none Postconditions: removes the first value in a queue ------------------------------------------------------------------------*/ void dequeue() { if ( !empty() ) { NodePointer ptr = myFront; myFront = myFront->next; delete ptr; if(myFront == NULL) myBack = NULL; } else { cerr << "*** Queue is empty -- " "can't remove a value ***\n"; exit(1); } } /*------------------------------------------------------------------------ pverloaded = operator Preconditions: requires a constant reference Postconditions: returns a const type T description: this allows assigning of queues to queues ------------------------------------------------------------------------*/ Queue<T> & operator=(const T &q) { // make sure we arent reassigning ourself // e.g. thisQueue = thisQueue. if(this != &q) { this->~Queue(); if(q.empty()) { myFront = myBack = NULL; } else { myFront = myBack = new Node(q.front()); NodePointer qPtr = q.myFront->next; while(qPtr != NULL) { myBack->next = new Node(qPtr->data); myBack = myBack->next; qPtr = qPtr->next; } } } return *this; } private: class Node { public: T data; Node * next; Node(T value, Node * first = 0) : data(value), next(first) {} }; typedef Node * NodePointer; NodePointer myFront, myBack, queueSize; }; /*------------------------------------------------------------------------ join Preconditions: requires 2 queue values Postconditions: appends queue2 to the end of queue1 description: this function joins 2 queues into 1. ------------------------------------------------------------------------*/ template <typename T> Queue<T> join(Queue<T> q1, Queue<T> q2) { Queue<T> q1Copy(q1), q2Copy(q2); Queue<T> jQueue; while(!q1Copy.empty()) { jQueue.enqueue(q1Copy.front()); q1Copy.dequeue(); } while(!q2Copy.empty()) { jQueue.enqueue(q2Copy.front()); q2Copy.dequeue(); } cout << jQueue << endl; return jQueue; } /*---------------------------------------------------------------------------- Overloaded << operator Preconditions: requires a constant reference and a Queue of type T Postconditions: returns the ostream (for chaining) description: this function is overloaded for outputing a queue with << ----------------------------------------------------------------------------*/ template <typename T> ostream & operator<<(ostream &out, Queue<T> &s) { s.display(out); return out; } /*---------------------------------------------------------------------------- Overloaded << operator Preconditions: requires a constant reference and a reference of type Student Postconditions: none description: this function is overloaded for outputing an object of type Student. ----------------------------------------------------------------------------*/ ostream & operator<<(ostream &out, Student &s) { s.display(out); } /*---------------------------------------------------------------------------- Overloaded << operator Preconditions: requires a constant reference and a reference of a pointer to a Student object. Postconditions: none description: this function is overloaded for outputing pointers to Students ----------------------------------------------------------------------------*/ ostream & operator<<(ostream &out, StudentPointer &s) { s->display(out); } #endif Now I'm having some issues with it. For one, when I add 0 to a queue and then I output the queue like so.. Queue<double> qdub; qdub.enqueue(0); cout << qdub << endl; That works, it will output 0. But for example, if I modify that queue in any way.. like.. assign it to a different queue.. Queue<double> qdub1; Queue<double> qdub2; qdub1.enqueue(0; qdub2 = qdub1; cout << qdub2 << endl; It will give me weird values for 0 like.. 7.86914e-316. Help on this would be much appreciated!

    Read the article

  • ListCtrl - wxPython / Python

    - by Francisco Aleixo
    Hello everyone. My question is if we can assign/bind some value to a certain item and hide that value(or if we can do the same thing in another way). Example: Lets say the columns on ListCtrl are "Name" and "Description": self.lc = wx.ListCtrl(self, -1, style=wx.LC_REPORT) self.lc.InsertColumn(0, 'Name') self.lc.InsertColumn(1, 'Description') And when I add a item I want them to show the Name parameter and the description: num_items = self.lc.GetItemCount() self.lc.InsertStringItem(num_items, "Randomname") self.lc.SetStringItem(num_items, 1, "Some description here") Now what I want to do is basically assign something to that item that is not shown so I can access later on the app. So I would like to add something that is not shown on the app but is on the item value like: hiddendescription = "Somerandomthing" Still didn't undestand? Well lets say I add a button to add a item with some other TextCtrls to set the parameters and the TextCtrls parameters are: "Name" "Description" "Hiddendescription" So then the user fills this textctrls out and clicks the button to create the item, and I basically want only to show the Name and Description and hide the "HiddenDescription" but to do it so I can use it later. Sorry for explaining more than 1 time on this post but I want to make sure you understand what I pretend to do.

    Read the article

  • Data of the web services in a RSS

    - by vymz
    I only have the .wsdl and I want to put the data that the web services return in the RSS. And in a web page of SAP, I can only upload RSS, so I need put the information of the web services in the RSS For example, I put the information manually(name and total value) in the fields <title> and <descripcion>, these data are extracted from the web services. But sometimes I don´t know how much information brings the web service. Also, I know that RSS is not to store information such as web services. <?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0"> <channel> <title>Test RSS</title> <link>http://solutions.com</link> <description>RSS</description> <item> <title>Luiz</title> <link>http://www.solutions.com/prueba1</link> <description>10</description> </item> <item> <title>Clodoaldo</title> <link>http://www.solutions.com/prueba2</link> <description>5</description> </item>

    Read the article

  • Problem while fetching xml through some rss feed

    - by Tariq- iPHONE Programmer
    I was fetching xml through some rss feed. I am unable to sort items in depth like i have sorted easily "channel - description" as NSString *resultValue=[[responseDictionary valueForKeyPath:@"rss.channel.description"] textContent]; Above Result: YouTube RSS Feed My question is how i can parse .... item - description... i.e (Music video by Andrews \U00a9 1982 MJJ Productions Inc.) i am getting nil if i fetch like valueForKeyPath:@"rss.channel.item.description"] Key: rss Value: { "_text" = "\n"; channel = { "_text" = "\n"; description = { "_text" = "YouTube RSS Feed"; }; item = ( { "_text" = "\n\t"; description = { "_text" = "Music video by Andrews \U00a9 1982 MJJ Productions Inc."; }; enclosure = { length = 294; type = "application/x-shockwave-flash"; url = "http://youtube.com/v/Zi_XLOBDo_Y.swf"; }; link = { "_text" = "http://youtube.com/?v=Zi_XLOBDo_Y"; };

    Read the article

  • F# Higher-order property accessors

    - by Nathan Sanders
    I just upgraded my prototyping tuple to a record. Someday it may become a real class. In the meantime, I want to translate code like this: type Example = int * int let examples = [(1,2); (3,4); (5,6)] let field1s = Seq.map (fst >> printfn "%d") examples to this: type Example = { Field1 : int Field2 : int Description : string } let examples = [{Field1 = 1; Field2 = 2; Description = "foo"} {Field1 = 3; Field2 = 4; Description = "bar"} {Field1 = 5; Field2 = 6; Description = "baz"}] let field1s = Seq.map Description examples The problem is that I expected to get a function Description : Example -> string when I declared the Example record, but I don't. I've poked around a little and tried properties on classes, but that doesn't work either. Am I just missing something in the documentation or will I have to write higher-order accessors manually? (That's the workaround I'm using now.)

    Read the article

  • How to work with CTE. There is some error related to anchor.

    - by Shantanu Gupta
    I am creating a hierarchy representaion of a column. But an error occurs Details are Msg 240, Level 16, State 1, Line 1 Types don't match between the anchor and the recursive part in column "DISPLAY" of recursive query "CTE". I know there is some typecasting error. But I dont know how to remove error. Please just dont only sort out my error. I need explanation why this error is coming. When this error occurs. I am trying to sort table on the basis of sort col that i m introducing. I want to add '-' at every level and want to sort accordingly. Please help WITH CTE (PK_CATEGORY_ID, [DESCRIPTION], FK_CATEGORY_ID, DISPLAY, SORT, DEPTH) AS ( SELECT PK_CATEGORY_ID, [DESCRIPTION], FK_CATEGORY_ID, '-' AS DISPLAY, '--' AS SORT, 0 AS DEPTH FROM dbo.L_CATEGORY_TYPE WHERE FK_CATEGORY_ID IS NULL UNION ALL SELECT T.PK_CATEGORY_ID, T.[DESCRIPTION], T.FK_CATEGORY_ID, CAST(DISPLAY+T.[DESCRIPTION] AS VARCHAR(1000)), '--' AS SORT, C.DEPTH +1 FROM dbo.L_CATEGORY_TYPE T JOIN CTE C ON C.PK_CATEGORY_ID = T.FK_CATEGORY_ID --SELECT T.PK_CATEGORY_ID, C.SORT+T.[DESCRIPTION], T.FK_CATEGORY_ID --, CAST('--' + C.SORT AS VARCHAR(1000)) AS SORT, CAST(DEPTH +1 AS INT) AS DEPTH --FROM dbo.L_CATEGORY_TYPE T JOIN CTE C ON C.FK_CATEGORY_ID = T.PK_CATEGORY_ID ) SELECT PK_CATEGORY_ID, [DESCRIPTION], FK_CATEGORY_ID, DISPLAY, SORT, DEPTH FROM CTE ORDER BY SORT

    Read the article

  • How to search within an xml data set?

    - by user187580
    Hi, I have some xml data and I am trying to keyword search data. For example, if I search "some" for the following data it returns me the <id> and <title>. <resource> <id>101</id> <title>Test Environment</title> <description><b>Some</b> description. </description> <type>classroom</type> </resource> <resource> <id>102</id> <title>ABC Test Environment</title> <description><b>Some</b> another description. </description> <type>classroom</type> </resource> ... I had a look on on xpath e.g. $xml->xpath('//title') but looks for elements only. Basically what I need to do is to create a functionality where users can keyword search within the above data set which I receive from third party api in the above format. Any ideas how I can achieve this? using PHP/ Javascript etc. Thanks.

    Read the article

  • Emacs hide/show support for C++ triple-slash Doxygen markup?

    - by jsyjr
    I use Doxygen's triple-slash syntax to markup my C++ code. There are two important cases which arise: 1) block markup comments which are the sole element on the line and may or may not begin flush left; e.g. class foo /// A one sentence brief description of foo. The elaboration can /// continue on for many lines. { ... }; void foo::bar /// A one sentence brief description of bar. The elaboration can /// continue on for many lines. () const { ... } 2) trailing markup comments which always follow some number of C++ tokens earlier on the first line but may still spill over onto subsequent lines; e.g. class foo { int _var1; ///< A brief description of _var1. int _var2; ///< A brief description of _var2 ///< requiring additional lines. } void foo::bar ( int arg1 ///< A brief description of arg1. , int arg2 ///< A brief description of arg2 ///< requiring additional lines. ) const { ... } I wonder what hide/show support exists to deal with these conventions. The most important cases are the block markup comments. Ideally I would like to be able to eliminate these altogether, meaning that I would prefer not to waste a line simply to indicate presence of a folded block markup comment. Instead I would like a fringe marker, a la http://www.emacswiki.org/emacs/hideshowvis.el /john

    Read the article

  • Query decendants in XML to Linq

    - by Gordon
    I have the following xml data: <portfolio> <item> <title>Site</title> <description>Site.com is a </description> <url>http://www.site.com</url> <photos> <photo url="http://www.site.com/site/thumbnail.png" thumbnail="true" description="Main" /> <photo url="http://www.site.com/site/1.png" thumbnail="false" description="Main" /> </photos> </item> </portfolio> In c# I am using the following link query: List list = new List(); XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/app_data/portfolio.xml")); list = (from portfolio in xmlDoc.Descendants("item") select new PortfolioItem() { Title = portfolio.Element("title").Value, Description = portfolio.Element("description").Value, Url = portfolio.Element("url").Value }).ToList(); How do I go about querying the photos node? In the PortfolioItem class I have a property: List Photos {get;set;} Any ideas would be greatly appreciated!

    Read the article

  • List of all states from COMPOSITE_INSTANCE, CUBE_INSTANCE, DLV_MESSAGE tables

    - by Deepak Arora
    In many of my engagements I get asked repeatedly about the states of the composites in 11g and how to decipher them, especially when we are troubleshooting issues around purging. I have compiled a list of all the states from the COMPOSITE_INSTANCE, CUBE_INSTANCE, and DLV_MESSAGE tables. These are the primary tables that are used when using BPEL composites and how they are used with the ECID.  Composite State Values COMPOSITE_INSTANCE States State Description 0 Running 1 Completed 2 Running with faults 3 Completed with faults 4 Running with recovery required 5 Completed with recovery required 6 Running with faults and recovery required 7 Completed with faults and recovery required 8 Running with suspended 9 Completed with suspended 10 Running with faults and suspended 11 Completed with faults and suspended 12 Running with recovery required and suspended 13 Completed with recovery required and suspended 14 Running with faults, recovery required, and suspended 15 Completed with faults, recovery required, and suspended 16 Running with terminated 17 Completed with terminated 18 Running with faults and terminated 19 Completed with faults and terminated 20 Running with recovery required and terminated 21 Completed with recovery required and terminated 22 Running with faults, recovery required, and terminated 23 Completed with faults, recovery required, and terminated 24 Running with suspended and terminated 25 Completed with suspended and terminated 26 Running with faulted, suspended, and terminated 27 Completed with faulted, suspended, and terminated 28 Running with recovery required, suspended, and terminated 29 Completed with recovery required, suspended, and terminated 30 Running with faulted, recovery required, suspended, and terminated 31 Completed with faulted, recovery required, suspended, and terminated 32 Unknown 64 - CUBE_INSTANCE States State Description 0 STATE_INITIATED 1 STATE_OPEN_RUNNING 2 STATE_OPEN_SUSPENDED 3 STATE_OPEN_FAULTED 4 STATE_CLOSED_PENDING_CANCEL 5 STATE_CLOSED_COMPLETED 6 STATE_CLOSED_FAULTED 7 STATE_CLOSED_CANCELLED 8 STATE_CLOSED_ABORTED 9 STATE_CLOSED_STALE 10 STATE_CLOSED_ROLLED_BACK DLV_MESSAGE States State Description 0 STATE_UNRESOLVED 1 STATE_RESOLVED 2 STATE_HANDLED 3 STATE_CANCELLED 4 STATE_MAX_RECOVERED Since now in 11g the Invoke_Messages table is not there so to distinguish between a new message (Invoke) and callback (DLV) and there is DLV_TYPE column that defines the type of message: DLV_TYPE States State Description 1 Invoke Message 2 DLV Message MEDIATOR_INSTANCE STATE Description  0  No faults but there still might be running instances  1  At least one case is aborted by user  2  At least one case is faulted (non-recoverable)  3  At least one case is faulted and one case is aborted  4  At least one case is in recovery required state  5 At least one case is in recovery required state and at least one is aborted  6 At least one case is in recovery required state and at least one is faulted  7 At least one case is in recovery required state, one faulted and one aborted  >=8 and < 16  Running >= 16   Stale In my next blog posting I will walk through the lifecycle of a BPEL process using the above states for the following use cases: - New BPEL process - initial Receive activity - Callback BPEL process - mid-level Receive activity As always comments and questions welcome! Deepak

    Read the article

  • SCVMM – Round 2 – How to create a Private Cloud using PowerShell

    - by Waclaw Chrabaszcz
    Originally posted on: http://geekswithblogs.net/Wchrabaszcz/archive/2013/06/28/scvmm--round-2--how-to-create-a-private.aspxHave you ever seen "A Bridge too far" movie? To not to wake up a click too far, it is good to script some tasks. Yes of course we can follow wizards, but some of us want to be warriorsJ. A small tip, take a look on credentials and system GUID examples. I don't know how about you, but for me it will be really useful in the future.    # credents$credential = Get-CredentialNew-SCRunAsAccount -Name "TESTDOMAIN\Administrator" -Credential $credential #storage $opsMgrServerCredential = Get-SCRunAsAccount -Name "TESTDOMAIN\Administrator"New-SCStorageClassification -Name "Bronze" -Description "" –RunAsynchronouslyNew-SCStorageClassification -Name "Silver" -Description "" –RunAsynchronouslyNew-SCStorageClassification -Name "Gold" -Description "" –RunAsynchronously # add a shared storageFind-SCComputer -ComputerName "dc.TESTDOMAIN.net"Add-SCStorageProvider -AddWindowsNativeWmiProvider -Name "dc.TESTDOMAIN.net" -RunAsAccount $opsMgrServerCredential -ComputerName "dc.TESTDOMAIN.net"$fileServer = Get-SCStorageFileServer "dc.TESTDOMAIN.net"$fileShares = @()$fileShares += Get-SCStorageFileShare -Name "VMMLibrary"Set-SCStorageFileServer -StorageFileServer $fileServer -AddStorageFileShareToManagement $fileShares –RunAsynchronously #fabric network$logicalNetwork = New-SCLogicalNetwork -Name "TESTDOMAIN-Service-Network" -LogicalNetworkDefinitionIsolation $false -EnableNetworkVirtualization $true -UseGRE $true -IsPVLAN $false$allHostGroups = @()$allHostGroups += Get-SCVMHostGroup -Name "All Hosts"$allSubnetVlan = @()$allSubnetVlan += New-SCSubnetVLan -Subnet "10.0.0.0/24" -VLanID 0New-SCLogicalNetworkDefinition -Name "TESTDOMAIN-Service-Network_0" -LogicalNetwork $logicalNetwork -VMHostGroup $allHostGroups -SubnetVLan $allSubnetVlan #IP pool$logicalNetwork = Get-SCLogicalNetwork -Name "TESTDOMAIN-Service-Network"$logicalNetworkDefinition = Get-SCLogicalNetworkDefinition -LogicalNetwork $logicalNetwork -Name "TESTDOMAIN-Service-Network_0" # Gateways$allGateways = @()$allGateways += New-SCDefaultGateway -IPAddress "10.0.0.1" –Automatic# DNS servers $allDnsServer = @("10.0.0.1")# DNS suffixes$allDnsSuffixes = @("TESTDOMAIN.net")# WINS servers$allWinsServers = @()New-SCStaticIPAddressPool -Name "TESTDOMAIN-Service-Network" -LogicalNetworkDefinition $logicalNetworkDefinition -Subnet "10.0.0.0/24" -IPAddressRangeStart "10.0.0.51" -IPAddressRangeEnd "10.0.0.75" -DefaultGateway $allGateways -DNSServer $allDnsServer -DNSSuffix "" -DNSSearchSuffix $allDnsSuffixes –RunAsynchronously #Hyper-V Virtual Networks$logicalNetwork = Get-SCLogicalNetwork -Name "TESTDOMAIN-Service-Network" $vmNetwork = New-SCVMNetwork -Name "TESTDOMAIN-VMN" -LogicalNetwork $logicalNetwork -IsolationType "WindowsNetworkVirtualization" -CAIPAddressPoolType "IPV4" -PAIPAddressPoolType "IPV4"Write-Output $vmNetwork$subnet = New-SCSubnetVLan -Subnet "10.0.0.0/24"New-SCVMSubnet -Name "Con-SN" -VMNetwork $vmNetwork -SubnetVLan $subnet # bind VLAN with the Network Adapter$vmHost = Get-SCVMHost -ComputerName "VMM01.TESTDOMAIN.net"$vmHostNetworkAdapter = Get-SCVMHostNetworkAdapter -VMHost $vmHost #-Name "Intel 21140-Based PCI Fast Ethernet Adapter (Emulated)"Set-SCVMHostNetworkAdapter -VMHostNetworkAdapter $vmHostNetworkAdapter -Description "" -AvailableForPlacement $true -UsedForManagement $true $logicalNetwork = Get-SCLogicalNetwork -Name "TESTDOMAIN-Service-Network" Set-SCVMHostNetworkAdapter -VMHostNetworkAdapter $vmHostNetworkAdapter -AddOrSetLogicalNetwork $logicalNetworkSet-SCVMHost -VMHost $vmHost -RunAsynchronously -NumaSpanningEnabled $true #Create a Private Cloud$Guid = [System.Guid]::NewGuid()Set-SCCloudCapacity -JobGroup $Guid -UseCustomQuotaCountMaximum $false -UseMemoryMBMaximum $false -UseCPUCountMaximum $false -UseStorageGBMaximum $false -UseVMCountMaximum $false -CustomQuotaCount 10 -MemoryMB 10240 -CPUCount 10 -StorageGB 386 -VMCount 10$resources = @()$resources += Get-SCLogicalNetwork -Name "TESTDOMAIN-Service-Network"$resources += Get-SCLoadBalancer -Manufacturer "Microsoft"$readonlyLibraryShares = @()$readonlyLibraryShares += Get-SCLibraryShare | where { $_.LibraryServer.Name -eq "dc.TESTDOMAIN.net" -and $_.Name -eq "VMMLibrary" }$addCapabilityProfiles = @()$addCapabilityProfiles += Get-SCCapabilityProfile -Name "Hyper-V"$Guid2 = [System.Guid]::NewGuid()Set-SCCloud -JobGroup $Guid2 -RunAsynchronously -AddCloudResource $resources -AddReadOnlyLibraryShare $readonlyLibraryShares -AddCapabilityProfile $addCapabilityProfiles$hostGroups = @()$hostGroups += Get-SCVMHostGroup -Name "TESTDOMAIN"New-SCCloud -VMHostGroup $hostGroups -Name "TESTDOMAIN-Cloud" -Description "" –RunAsynchronously

    Read the article

  • NSInvalidArgumentException: *** -[NSPlaceholderString initWithFormat:locale:arguments:]: nil argumen

    - by BU
    I have no idea where in my code is causing this problem. Can someone please take a look and let me know what I am missing? The code is relatively straightforward. +(void)processGetGameOffersByGameWithReply:(NSDictionary *)responseDictionary { GameOffer *gameOffer; @try { SharedResources *s = [SharedResources instance]; GameOffersByGameTableViewController *gameOffersByGameTableViewController = [s gameOffersByGameTableViewController]; NSMutableArray *gameOffersArray = [gameOffersByGameTableViewController gameOffersAsArray]; NSString *dealsCountString = [[responseDictionary valueForKey:@"number_of_deals"] retain]; NSNumber *dealsCount = [[SharedResources convertToNumberFromString:dealsCountString] retain]; int i=0; NSString *keyStringForTitle; NSString *title, *description, *keyStringForDescription; for(int i=0; i < dealsCount; i++) { /*NSString *keyStringForDealID = [NSString stringWithFormat:@"DealID%d", i]; NSString *DealIDString = [responseDictionary valueForKey:keyStringForDealID]; NSNumber *DealID = [[SharedResources convertToNumberFromString:DealIDString] retain];*/ keyStringForTitle = [[NSString alloc] initWithFormat:@"Title%d",i] ; title = [[NSString alloc] initWithFormat:[responseDictionary valueForKey:keyStringForTitle]]; //[[responseDictionary valueForKey:keyStringForTitle] retain]; keyStringForDescription = [[NSString alloc] initWithFormat:@"Description%d", i]; description = [[NSString alloc] initWithFormat:[responseDictionary valueForKey:keyStringForDescription]]; /*NSString *keyStringForGameID = [NSString stringWithFormat:@"GameID%d", i]; NSString *GameIDString = [responseDictionary valueForKey:keyStringForGameID]; NSNumber *GameID = [[SharedResources convertToNumberFromString:GameIDString] retain];*/ gameOffer = [[GameOffer alloc] initWithTitle:title Description:description Image:nil]; //int i =0; SharedResources *s = [SharedResources instance]; [gameOffersArray addObject:[gameOffer retain]]; int j=0; } NSString *temp = nil; int k = 0; //find the navigation controller UINavigationController *myNavigationController = [[s gamesTableViewController] navigationController]; //push the table view controller to the navigation controller; [myNavigationController pushViewController:gameOffersByGameTableViewController animated:YES]; } @catch (NSException *ex) { NSLog(@"Count is %d", [[[[SharedResources instance] gameOffersByGameTableViewController] gameOffersAsArray] count]); NSLog(@"\n%@\n%@", [gameOffer Title], [gameOffer Description] ); [SharedResources LogException:ex]; } } The problem is whenever the program gets done with the for loop, it doesn't execute the "NSString *temp=nil" anymore, it jumps to the catch statement. I tried removing the for loop setting i = 0. The problem doesn't occur anymore. It reaches teh end of the method by adding only one object in the array. The problem only occurs if there's a for loop. In the catch statement, even with the error, I can see that the array is filled properly and the [gameOffer Title] and [gameOffer Description] have the correct values. Thanks so much for your help.

    Read the article

  • Spring MVC return ajax response using Jackson

    - by anshumn
    I have a scenario where I am filling a dropdown box in JSP through AJAX response from the server. In the controller, I am retuning a Collection of Product objects and have annotated the return type with @ResponseBody. Controller - @RequestMapping(value="/getServicesForMarket", method = RequestMethod.GET) public @ResponseBody Collection<Product> getServices(@RequestParam(value="marketId", required=true) int marketId) { Collection<Product> products = marketService.getProducts(marketId); return products; } And Product is @Entity @Table(name = "PRODUCT") public class Product implements Serializable { private static final long serialVersionUID = 1L; private int id; private Market market; private Service service; private int price; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "MARKET_ID") public Market getMarket() { return market; } public void setMarket(Market market) { this.market = market; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "SERVICE_ID") public Service getService() { return service; } public void setService(Service service) { this.service = service; } @Column(name = "PRICE") public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } Service is @Entity @Table(name="SERVICE") public class Service implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private String description; @Id @GeneratedValue @Column(name="ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="DESCRIPTION") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } In the JSP, I need to get the data from the service field of Product also. So I in my JQuery callback function, I have written like product.service.description to get the data. It seems that by default Jackson is not mapping the associated service object (or any other custom object). Also I am not getting any exception. In the JSP, I do not get the data. It is working fine when I return Collection of some object which does not contain any other custom objects as its fields. Am I missing any settings for this to work? Thanks!

    Read the article

  • SQLiteException and SQLite error near "(": syntax error with Subsonic ActiveRecord

    - by nvuono
    I ran into an interesting error with the following LiNQ query using LiNQPad and when using Subsonic 3.0.x w/ActiveRecord within my project and wanted to share the error and resolution for anyone else who runs into it. The linq statement below is meant to group entries in the tblSystemsValues collection into their appropriate system and then extract the system with the highest ID. from ksf in KeySafetyFunction where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystems on ksf.ID equals sys.KeySafetyFunction join xval in (from t in tblSystemsValues group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g=>g.ID), MaxText = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).Checked }) on sys.ID equals xval.sysId select new {KSFDesc=ksf.Description, sys.Description, xval.MaxText, xval.MaxChecked} On its own, the subquery for grouping into groupedT works perfectly and the query to match up KeySafetyFunctions with their System in tblSystems also works perfectly on its own. However, when trying to run the completed query in linqpad or within my project I kept running into a SQLiteException SQLite Error Near "(" First I tried splitting the queries up within my project because I knew that I could just run a foreach loop over the results if necessary. However, I continued to receive the same exception! I eventually separated the query into three separate parts before I realized that it was the lazy execution of the queries that was killing me. It then became clear that adding the .ToList() specifier after the myProtectedSystem query below was the key to avoiding the lazy execution after combining and optimizing the query and being able to get my results despite the problems I encountered with the SQLite driver. // determine the max Text/Checked values for each system in tblSystemsValue var myProtectedValue = from t in tblSystemsValue.All() group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g => g.ID), MaxText = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).Checked}; // get the system description information and filter by Unit/Condition ID var myProtectedSystem = (from ksf in KeySafetyFunction.All() where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystem.All() on ksf.ID equals sys.KeySafetyFunction select new {KSFDesc = ksf.Description, sys.Description, sys.ID}).ToList(); // finally join everything together AFTER forcing execution with .ToList() var joined = from protectedSys in myProtectedSystem join protectedVal in myProtectedValue on protectedSys.ID equals protectedVal.sysId select new {protectedSys.KSFDesc, protectedSys.Description, protectedVal.MaxChecked, protectedVal.MaxText}; // print the gratifying debug results foreach(var protectedItem in joined) { System.Diagnostics.Debug.WriteLine(protectedItem.Description + ", " + protectedItem.KSFDesc + ", " + protectedItem.MaxText + ", " + protectedItem.MaxChecked); }

    Read the article

  • How to make a composite Zend Form Element that includes a Dojo Field

    - by Joe
    I used the zendcast video to get me this far. The form is properly displayed. However, I need to change the display order box into a number box of zend dojo type. I cannot figure it out. Even help with examples would be great. <?php class My_View_Helper_CategoryDetailElement extends Zend_View_Helper_FormElement { protected $html = ''; public function CategoryDetailElement($name, $value = null, $attribs = null) { $type = $description = $displayOrder = $time = ''; if($value) { $type = $value->type; $description = $value->description; $displayOrder = $value->displayOrder; $time = $value->time; } $helper = new Zend_View_Helper_FormText(); $helper->setView($this->view); $helper_label = new Zend_View_Helper_FormLabel(); $helper_label->setView($this->view); $helper_select = new Zend_View_Helper_FormSelect(); $helper_select->setView($this->view); $helper_textarea = new Zend_View_Helper_FormTextarea(); $helper_textarea->setView($this->view); $this->html .= $helper_label->formLabel($name . '[type]', 'Type: ', array()); $this->html .= $helper_select->formSelect($name . '[type]', $type, array(), array('individual'=>'individual', 'team'=>'team')); $this->html .= "<br />"; $this->html .= $helper_label->formLabel($name . '[description]', 'Description: ', array()); $this->html .= $helper_textarea->formTextarea($name . '[description]', $description, array()); $this->html .= "<br />"; $this->html .= $helper_label->formLabel($name . '[displayOrder]', 'Display Order: ', array()); $this->html .= $helper->formText($name . '[displayOrder]', $displayOrder, array()); $this->html .= "<br />"; $this->html .= $helper_label->formLabel($name . '[time]', 'Time: ', array()); $this->html .= $helper->formText($name . '[time]', $time, array()); return $this->html; } } ?>

    Read the article

  • CommandName issues to insert to a database

    - by Alexander
    In the below code, when we define the parameters CommandName="Insert" is it actually the same as executing the method Insert? As I can't find Insert anywhere... <div class="actionbuttons"> <Club:RolloverButton ID="apply1" CommandName="Insert" Text="Add Event" runat="server" /> <Club:RolloverLink ID="Cancel" Text="Cancel" runat="server" NavigateURL='<%# "Events_view.aspx?EventID=" + Convert.ToString(Eval("ID")) %>' /> </div> I have the following SqlDataSource as well: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ClubSiteDB %>" SelectCommand="SELECT dbo.Events.id, dbo.Events.starttime, dbo.events.endtime, dbo.Events.title, dbo.Events.description, dbo.Events.staticURL, dbo.Events.photo, dbo.Events.location, dbo.Locations.title AS locationname FROM dbo.Events LEFT OUTER JOIN dbo.Locations ON dbo.Events.location = dbo.Locations.id where Events.id=@id" InsertCommand="INSERT INTO Events(starttime, endtime, title, description, staticURL, location, photo) VALUES (@starttime, @endtime, @title, @description, @staticURL, @location, @photo)" UpdateCommand="UPDATE Events SET starttime = @starttime, endtime=@endtime, title = @title, description = @description, staticURL = @staticURL, location = @location, photo = @photo WHERE (id = @id)" DeleteCommand="DELETE Events WHERE id=@id" OldValuesParameterFormatString="{0}"> <SelectParameters> <asp:QueryStringParameter Name="id" QueryStringField="ID" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="starttime" Type="DateTime" /> <asp:Parameter Name="endtime" Type="DateTime" /> <asp:Parameter Name="title" /> <asp:Parameter Name="description" /> <asp:Parameter Name="staticURL" /> <asp:Parameter Name="location" /> <asp:Parameter Name="photo" /> <asp:Parameter Name="id" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="starttime" Type="DateTime" /> <asp:Parameter Name="endtime" Type="DateTime" /> <asp:Parameter Name="title" /> <asp:Parameter Name="description" /> <asp:Parameter Name="staticURL" /> <asp:Parameter Name="location" /> <asp:Parameter Name="photo" /> <asp:Parameter Name="id" /> </InsertParameters> <DeleteParameters> <asp:QueryStringParameter Name="id" QueryStringField="ID" /> </DeleteParameters> </asp:SqlDataSource> I want it to insert using the InsertCommand, however when I do SqlDataSource1.Insert() it's complaining that starttime is NULL

    Read the article

  • Javascript to add cdata section on the fly?

    - by Chris G.
    I'm having trouble with special characters that exist in an xml node attribute. To combat this, I'm trying to render the attributes as child nodes and, where necessary, using cdata sections to get around the special characters. The problem is, I can't seem to get the cdata section appended to the node correctly. I'm iterating over the source xml node's attributes and creating new nodes. If the attribute.name = "description" I want to put the attribute.text() in a cdata section and append the new node. That's where I jump the track. // newXMLData is the new xml document that I've created in memory for (var ctr =0;ctr< this.attributes.length;ctr++){ // iterate over the attributes if( this.attributes[ctr].name =="Description"){ // if the attribute name is "Description" add a CDATA section var thisNodeName = this.attributes[ctr].name; newXMLDataNode.append("<"+thisNodeName +"></"+ thisNodeName +">" ); var cdata = newXMLData.createCDATASection('test'); // here's where it breaks. } else { // It's not "Description" so just append the new node. newXMLDataNode.append("<"+ this.attributes[ctr].name +">" + $(this.attributes[ctr]).text() + "</"+ this.attributes[ctr].name +">" ); } } Any ideas? Is there another way to add a cdata section? Here's a sample snippet of the source... <row pSiteID="4" pSiteTile="Test Site Name " pSiteURL="http://www.cnn.com" ID="1" Description="<div>blah blah blah since June 2007.&amp;nbsp; T<br>&amp;nbsp;<br>blah blah blah blah&amp;nbsp; </div>" CreatedDate="2010-09-20 14:46:18" Comments="Comments example.&#10;" > here's what I'm trying to create... <Site> <PSITEID>4</PSITEID> <PSITETILE>Test Site Name</PSITETILE> <PSITEURL>http://www.cnn.com</PSITEURL> <ID>1</ID> <DESCRIPTION><![CDATA[<div>blah blah blah since June 2007.&amp;nbsp; T<br>&amp;nbsp;<br>blah blah blah blah&amp;nbsp; </div ]]></DESCRIPTION> <CREATEDDATE>2010-09-20 14:46:18</CREATEDDATE> <COMMENTS><![CDATA[ Comments example.&#10;]]></COMMENTS> </Site>

    Read the article

  • fieldWithErrors not wrapping every error field

    - by Teef L
    Notice the following result when I submit blank :title and :description fields The validations are in the controller: class Question < ActiveRecord::Base validates_presence_of :title validates_presence_of :description And, the form is generated with those names: -form_for(@question) do |f| = f.error_messages = f.label :title = f.text_field :title, :size => 50, :onchange => remote_function(:url => {:action => :display_tag_suggestions}, :with => 'Form.Element.serialize(this)') #suggestions = f.label :description = f.text_area :description ... But, for some reason, only :title gets wrapped in the error div tags: <form action="/questions" class="new_question" id="new_question" method="post"> <div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="6HQaiu1D0gBQcKw2pLeZP6Jvn0FSClPD5Sk9HwegzPg=" /></div> <div class="errorExplanation" id="errorExplanation"> <h2>2 errors prohibited this question from being saved</h2> <p>There were problems with the following fields:</p> <ul> <li>Title can't be blank</li> <li>Description can't be blank</li> </ul> </div> <label for="question_title">Title</label> <div class="fieldWithErrors"><input id="question_title" name="question[title]" onchange="new Ajax.Request('/questions/display_tag_suggestions', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(this) + '&amp;authenticity_token=' + encodeURIComponent('6HQaiu1D0gBQcKw2pLeZP6Jvn0FSClPD5Sk9HwegzPg=')})" size="50" type="text" value="" /></div> <label for="question_description">Description</label> <textarea cols="40" id="question_description" name="question[description]" rows="20"></textarea> ... I don't think that behavior is expected. The problem most people have is that it's wrapping things with divs, which won't display properly. My problem is that fields aren't being wrapped with divs to begin with! I haven't made any (conscious) changes to how errors are handled, so I'm not sure why it's not working properly.

    Read the article

  • Writing Unit Tests for ASP.NET Web API Controller

    - by shiju
    In this blog post, I will write unit tests for a ASP.NET Web API controller in the EFMVC reference application. Let me introduce the EFMVC app, If you haven't heard about EFMVC. EFMVC is a simple app, developed as a reference implementation for demonstrating ASP.NET MVC, EF Code First, ASP.NET Web API, Domain-Driven Design (DDD), Test-Driven Development (DDD). The current version is built with ASP.NET MVC 4, EF Code First 5, ASP.NET Web API, Autofac, AutoMapper, Nunit and Moq. All unit tests were written with Nunit and Moq. You can download the latest version of the reference app from http://efmvc.codeplex.com/ Unit Test for HTTP Get Let’s write a unit test class for verifying the behaviour of a ASP.NET Web API controller named CategoryController. Let’s define mock implementation for Repository class, and a Command Bus that is used for executing write operations.  [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } The code block below provides the unit test for a HTTP Get operation. [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        The GetCategories method is provided below: private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } In the unit test method Get_All_Returns_AllCategory, we specify setup on the mocked type ICategoryrepository, for a call to GetCategoryWithExpenses method returns dummy data. We create an instance of the ApiController, where we have specified the Request property of the ApiController since the Request property is used to create a new HttpResponseMessage that will provide the appropriate HTTP status code along with response content data. Unit Tests are using for specifying the behaviour of components so that we have specified that Get operation will use the model type IEnumerable<CategoryWithExpense> for sending the Content data. The implementation of HTTP Get in the CategoryController is provided below: public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; } Unit Test for HTTP Post The following are the behaviours we are going to implement for the HTTP Post: A successful HTTP Post  operation should return HTTP status code Created An empty Category should return HTTP status code BadRequest A successful HTTP Post operation should provide correct Location header information in the response for the newly created resource. Writing unit test for HTTP Post is required more information than we write for HTTP Get. In the HTTP Post implementation, we will call to Url.Link for specifying the header Location of Response as shown in below code block. var response = Request.CreateResponse(HttpStatusCode.Created, category); string uri = Url.Link("DefaultApi", new { id = category.CategoryId }); response.Headers.Location = new Uri(uri); return response; While we are executing Url.Link from unit tests, we have to specify HttpRouteData information from the unit test method. Otherwise, Url.Link will get a null value. The code block below shows the unit tests for specifying the behaviours for the HTTP Post operation. [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } In the above code block, we have written two unit methods, Post_Category_Returns_CreatedStatusCode and Post_EmptyCategory_Returns_BadRequestStatusCode. The unit test method Post_Category_Returns_CreatedStatusCode  verifies the behaviour 1 and 3, that we have defined in the beginning of the section “Unit Test for HTTP Post”. The unit test method Post_EmptyCategory_Returns_BadRequestStatusCode verifies the behaviour 2. For extracting the data from response, we call Content.ReadAsStringAsync().Result of HttpResponseMessage object and deserializeit it with Json Convertor. The implementation of HTTP Post in the CategoryController is provided below: // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); } The unit test implementation for HTTP Put and HTTP Delete are very similar to the unit test we have written for  HTTP Get. The complete unit tests for the CategoryController is given below: [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        [Test] public void Get_CorrectCategoryId_Returns_Category() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(1);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);     var category = JsonConvert.DeserializeObject<CategoryWithExpense>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(1, category.CategoryId, "Got wrong number of Categories"); } [Test] public void Get_InValidCategoryId_Returns_NotFound() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(5);     // Assert     Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);            } [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } [Test] public void Put_Category_Returns_OKStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Put(category.CategoryId,category);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);    } [Test] public void Delete_Category_Returns_NoContentStatusCode() {     // Arrange              commandBus.Setup(c => c.Submit(It.IsAny<DeleteCategoryCommand >())).Returns(new CommandResult(true));     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act               var response = controller.Delete(1);     // Assert     Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);   } private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } }  The complete implementation for the Api Controller, CategoryController is given below: public class CategoryController : ApiController {       private readonly ICommandBus commandBus;     private readonly ICategoryRepository categoryRepository;     public CategoryController(ICommandBus commandBus, ICategoryRepository categoryRepository)     {         this.commandBus = commandBus;         this.categoryRepository = categoryRepository;     } public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; }   // GET /api/category/5 public HttpResponseMessage Get(int id) {     var category = categoryRepository.GetCategoryWithExpenses().Where(c => c.CategoryId == id).SingleOrDefault();     if (category == null)     {         return Request.CreateResponse(HttpStatusCode.NotFound);     }     return Request.CreateResponse(HttpStatusCode.OK, category); }   // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }   // PUT /api/category/5 public HttpResponseMessage Put(int id, CategoryModel category) {     if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         return Request.CreateResponse(HttpStatusCode.OK, category);     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }       // DELETE /api/category/5     public HttpResponseMessage Delete(int id)     {         var command = new DeleteCategoryCommand { CategoryId = id };         var result = commandBus.Submit(command);         if (result.Success)         {             return new HttpResponseMessage(HttpStatusCode.NoContent);         }             throw new HttpResponseException(HttpStatusCode.BadRequest);     } } Source Code The EFMVC app can download from http://efmvc.codeplex.com/ . The unit test project can be found from the project EFMVC.Tests and Web API project can be found from EFMVC.Web.API.

    Read the article

  • Include weather information in ASP.Net site from weather.com services

    - by sreejukg
    In this article, I am going to demonstrate how you can use the XMLOAP services (referred as XOAP from here onwards) provided by weather.com to display the weather information in your website. The XOAP services are available to be used for free of charge, provided you are comply with requirements from weather.com. I am writing this article from a technical point of view. If you are planning to use weather.com XOAP services in your application, please refer to the terms and conditions from weather.com website. In order to start using the XOAP services, you need to sign up the XOAP datafeed. The signing process is simple, you simply browse the url http://www.weather.com/services/xmloap.html. The URL looks similar to the following. Click on the sign up button, you will reach the registration page. Here you need to specify the site name you need to use this feed for. The form looks similar to the following. Once you fill all the mandatory information, click on save and continue button. That’s it. The registration is over. You will receive an email that contains your partner id, license key and SDK. The SDK available in a zipped format, contains the terms of use and documentation about the services available. Other than this the SDK includes the logos and icons required to display the weather information. As per the SDK, currently there are 2 types of information available through XOAP. These services are Current Conditions for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Hourly Five-Day Forecast (today + 4 additional forecast days in consecutive order beginning with tomorrow) for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Three Times Daily The SDK provides detailed information about the fields included in response of each service. Additionally there is a refresh rate that you need to comply with. As per the SDK, the refresh rate means the following “Refresh Rate” shall mean the maximum frequency with which you may call the XML Feed for a given LocID requesting a data set for that LocID. During the time period in between refresh periods the data must be cached by you either in the memory on your servers or in Your Desktop Application. About the Services Weather.com will provide you with access to the XML Feed over the Internet through the hostname xoap.weather.com. The weather data from the XML feed must be requested for a specific location. So you need a location ID (LOC ID). The XML feed work with 2 types of location IDs. First one is with City Identifiers and second one is using 5 Digit US postal codes. If you do not know your location ID, don’t worry, there is a location id search service available for you to retrieve the location id from city name. Since I am a resident in the Kingdom of Bahrain, I am going to retrieve the weather information for Manama(the capital of Bahrain) . In order to get the location ID for Manama, type the following URL in your address bar. http://xoap.weather.com/search/search?where=manama I got the following XML output. <?xml version="1.0" encoding="UTF-8"?> <!-- This document is intended only for use by authorized licensees of The –> <!-- Weather Channel. Unauthorized use is prohibited. Copyright 1995-2011, –> <!-- The Weather Channel Interactive, Inc. All Rights Reserved. –> <search ver="3.0">       <loc id="BAXX0001" type="1">Al Manama, Bahrain</loc> </search> You can try this with any city name, if the city is available, it will return the location id, and otherwise, it will return nothing. In order to get the weather information, from XOAP,  you need to pass certain parameters to the XOAP service. A brief about the parameters are as follows. Please refer SDK for more details. Parameter name Possible Value cc Optional, if you include this, the current condition will be returned. Value can be anything, as it will be ignored e.g. cc=* dayf If you want the forecast for 5 days, specify dayf=5 This is optional iink Value should be XOAP par Your partner id. You can find this in your registration email from weather.com prod Value should be XOAP key The license key assigned to you. This will be available in the registration email unit s or m (standard or matric or you can think of Celsius/Fahrenheit) this is optional field, if not specified the unit will be standard(s) The URL host for the XOAP service is http://xoap.weather.com. So for my purpose, I need the following request to be made to access the XOAP services. http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=*********&key=************** (The ***** to be replaced with the corresponding alternatives) The response XML have a root element “weather”. Under the root element, it has the following sections <head> - the meta data information about the weather results returned. <loc> - the location data block that provides, the information about the location for which the wheather data is retrieved. <lnks> - the 4 promotional links you need to place along with the weather display. Additional to these 4 links, there should be another link with weather channel logo to the home page of weather.com. <cc> - the current condition data. This element will be there only if you specify the cc element in the request. <dayf> - the forcast data as you specified. This element will be there only if you specify the dayf in the request. In this walkthrough, I am going to capture the weather information for Manama (Location ID: BAXX0001). You need 2 applications to display weather information in your website. A Console application that retrieves data from the XMLOAP and store in the SQL Server database (or any data store as you prefer).This application will be scheduled to execute in every 25 minutes using windows task scheduler, so that we can comply with the refresh rate. A web application that display data from the SQL Server database Retrieve the Weather from XOAP I have created a console application named, Weather Service. I created a SQL server database, with the following columns. I named the table as tblweather. You are free to choose any name. Column name Description lastUpdated Datetime, this is the last time when the weather data is updated. This is the time of the service running TemparatureDateTime The date and time returned by XML feed Temparature The temperature returned by the XML feed. TemparatureUnit The unit of the temperature returned by the XML feed iconId The id of the icon to be used. Currently 48 icons from 0 to 47 are available. WeatherDescription The Weather Description Phrase returned by the feed. Link1url The url to the first promo link Link1Text The text for the first promo link Link2url The url to the second promo link Link2Text The text for the second promo link Link3url The url to the third promo link Link3Text The text for the third promo link Link4url The url to the fourth promo link Link4Text The text for the fourth promo link Every time when the service runs, the application will update the database columns from the XOAP data feed. When the application starts, It is going to get the data as XML from the url. This demonstration uses LINQ to extract the necessary data from the fetched XML. The following are the code segment for extracting data from the weather XML using LINQ. // first, create an instance of the XDocument class with the XOAP URL. replace **** with the corresponding values. XDocument weather = XDocument.Load("http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=***********&key=c*********"); // construct a query using LINQ var feedResult = from item in weather.Descendants() select new { unit = item.Element("head").Element("ut").Value, temp = item.Element("cc").Element("tmp").Value, tempDate = item.Element("cc").Element("lsup").Value, iconId = item.Element("cc").Element("icon").Value, description = item.Element("cc").Element("t").Value, links = from link in item.Elements("lnks").Elements("link") select new { url = link.Element("l").Value, text = link.Element("t").Value } }; // Load the root node to a variable, you may use foreach construct instead. var item1 = feedResult.First(); *If you want to learn more about LINQ and XML, read this nice blog from Scott GU. http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx Now you have all the required values in item1. For e.g. if you want to get the temperature, use item1.temp; Now I just need to execute an SQL query against the database. See the connection part. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { string strSql = @"update tblweather set lastupdated=getdate(), temparatureDateTime = @temparatureDateTime, temparature=@temparature, temparatureUnit=@temparatureUnit, iconId = @iconId, description=@description, link1url=@link1url, link1text=@link1text, link2url=@link2url, link2text=@link2text,link3url=@link3url, link3text=@link3text,link4url=@link4url, link4text=@link4text"; SqlCommand comm = new SqlCommand(strSql, conn); comm.Parameters.AddWithValue("temparatureDateTime", item1.tempDate); comm.Parameters.AddWithValue("temparature", item1.temp); comm.Parameters.AddWithValue("temparatureUnit", item1.unit); comm.Parameters.AddWithValue("description", item1.description); comm.Parameters.AddWithValue("iconId", item1.iconId); var lstLinks = item1.links; comm.Parameters.AddWithValue("link1url", lstLinks.ElementAt(0).url); comm.Parameters.AddWithValue("link1text", lstLinks.ElementAt(0).text); comm.Parameters.AddWithValue("link2url", lstLinks.ElementAt(1).url); comm.Parameters.AddWithValue("link2text", lstLinks.ElementAt(1).text); comm.Parameters.AddWithValue("link3url", lstLinks.ElementAt(2).url); comm.Parameters.AddWithValue("link3text", lstLinks.ElementAt(2).text); comm.Parameters.AddWithValue("link4url", lstLinks.ElementAt(3).url); comm.Parameters.AddWithValue("link4text", lstLinks.ElementAt(3).text); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); Console.WriteLine("database updated"); } Now click ctrl + f5 to run the service. I got the following output Check your database and make sure, the data is updated with the latest information from the service. (Make sure you inserted one row in the database by entering some values before executing the service. Otherwise you need to modify your application code to count the rows and conditionally perform insert/update query) Display the Weather information in ASP.Net page Now you got all the data in the database. You just need to create a web application and display the data from the database. I created a new ASP.Net web application with a default.aspx page. In order to comply with the terms of weather.com, You need to use Weather.com logo along with the weather display. You can find the necessary logos to use under the folder “logos” in the SDK. Additionally copy any of the icon set from the folder “icons” to your web application. I used the 93x93 icon set. You are free to use any other sizes available. The design view of the page in VS2010 looks similar to the following. The page contains a heading, an image control (for displaying the weather icon), 2 label controls (for displaying temperature and weather description), 4 hyperlinks (for displaying the 4 promo links returned by the XOAP service) and weather.com logo with hyperlink to the weather.com home page. I am going to write code that will update the values of these controls from the values stored in the database by the service application as mentioned in the previous step. Go to the code behind file for the webpage, enter the following code under Page_Load event handler. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { SqlCommand comm = new SqlCommand("select top 1 * from tblweather", conn); conn.Open(); SqlDataReader reader = comm.ExecuteReader(); if (reader.Read()) { lblTemparature.Text = reader["temparature"].ToString() + "&deg;" + reader["temparatureUnit"].ToString(); lblWeatherDescription.Text = reader["description"].ToString(); imgWeather.ImageUrl = "icons/" + reader["iconId"].ToString() + ".png"; lnk1.Text = reader["link1text"].ToString(); lnk1.NavigateUrl = reader["link1url"].ToString(); lnk2.Text = reader["link2text"].ToString(); lnk2.NavigateUrl = reader["link2url"].ToString(); lnk3.Text = reader["link3text"].ToString(); lnk3.NavigateUrl = reader["link3url"].ToString(); lnk4.Text = reader["link4text"].ToString(); lnk4.NavigateUrl = reader["link4url"].ToString(); } conn.Close(); } Press ctrl + f5 to run the page. You will see the following output. That’s it. You need to configure the console application to run every 25 minutes so that the database is updated. Also you can fetch the forecast information and store those in the database, and then retrieve it later in your web page. Since the data resides in your database, you have the full control over your display. You need to make sure your website comply with weather.com license requirements. If you want to get the source code of this walkthrough through the application, post your email address below. Hope you enjoy the reading.

    Read the article

  • Issue configuring Oracle database for SSL

    - by Santhosha Kaldambe
    Hello, I want to setup Oracle for SSL communication. I am not using SSL authentication for database user. As first requirement, generated self signed certificate using OpenSSL and added certificate to wallet. The wallet location is specified in server configuration. Created listener and it is starting however it does not provide any service. The default listener (non SSL) is working fine. When I execute LSNRCTL.EXE status SSLLISTENER it gives below output. STATUS of the LISTENER Alias SSLLISTENER Version TNSLSNR for 32-bit Windows: Version 11.1.0.6.0 - Production Start Date 14-NOV-2009 01:47:08 Uptime 16 days 22 hr. 14 min. 3 sec Trace Level off Security ON: Local OS Authentication SNMP OFF Listener Parameter File C:\app\Administrator\product\11.1.0\db_1\network\admin\listener.ora Listener Log File c:\app\administrator\diag\tnslsnr\\ssllistener\alert\log.xml Listening Endpoints Summary... (DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=)(PORT =2484))) The listener supports no services The command completed successfully Here is exact content of various files after configuration. 1) File Name: tnsnames.ora ORCL = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT 1521)) ) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = orcl) ) ) 2) File Name: sqlnet.ora SSL_VERSION = 0 NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT) sqlnet.authentication_services= (NONE) tcp.validnode_checking = no tcp.invited_nodes=(PS0803.oraebs.com,PS2948,PS5098) SSL_CLIENT_AUTHENTICATION = FALSE WALLET_LOCATION = (SOURCE = (METHOD = FILE) (METHOD_DATA = (DIRECTORY = C:\app\Administrator\admin\orcl\Server_Wallet) ) ) 3) File Name: listener.ora SSL_CLIENT_AUTHENTICATION = FALSE WALLET_LOCATION = (SOURCE = (METHOD = FILE) (METHOD_DATA = (DIRECTORY = C:\app\Administrator\admin\orcl\Server_Wallet) ) ) LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT 1521)) ) ) SSLLISTENER = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCPS)(HOST = )(PORT = 2484)) ) Thanks Santhosh

    Read the article

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