14 Aralık 2015 Pazartesi

WPF-XmlDataProvider ile Veri Sorgulama

XmlDataProvider sayesinde wpf uygulamalarımızda xml veritabanında bulunan kayıtları okuyup üzerinde sorgular yapabilmekteyiz. Dilerseniz vakit kaybetmeden bu nesnenin nasıl kullanıldığıyla ilgili örnek bir senaryo üzerinden gidelim. Aşağıdaki gibi bir xml veritabanımızın olduğunu düşünelim.

<?xml version="1.0" encoding="utf-8" ?>
<Games>
         <Game ID="1" For="PC">
                 <Name>Pro Evolution Soccer 11</Name>
                 <Price>169$</Price>
         </Game>
         <Game ID="2" For="PS">
                 <Name>Need For Speed Most Wanted </Name>
                 <Price>89$</Price>
         </Game>
         <Game ID="3" For="PS">
                 <Name>Call Of Duty Modern Warfare</Name>
                 <Price>139$</Price>
         </Game>
         <Game ID="4" For="PC">
                 <Name>Fifa 2011</Name>
                 <Price>119$</Price>
         </Game>
         <Game ID="5" For="PS">
                 <Name>Crysis 2</Name>
                 <Price>120$</Price>
         </Game>
</Games>

Xml dosyamızdaki oyunları ve fiyatlarını XmlDataProvider nesnesi ile nasıl çekebileceğimize gözatalım. Öncelikle bir XmlDataProvider nesnesi oluşturup kaynağını verilerimizin bulunduğu xml dosyası olarak göstermemiz gerekmektedir. Xml dosyamızın yerini belirttikten sonra hangi düğümden veri çekeceğimizi belirtmemizi sağlayan XPath özelliğini kullanacağız. Ben verileri listelemek için ItemsControl kullandım. XmlDataProvider nesnesini UserControl'ümün kaynağında tanımladıktan sonra ItemsControl'ün ItemsSource özelliğine atıyorum. Tüm bunları yaptıktan sonra aşağıdakine gibi bir ekran çıktısına sahip oluyoruz.

<Grid>
        <Grid.Resources>
            <XmlDataProvider x:Key="dataResource"
             XPath="Games/Game" Source="GameData.xml"/>
        </Grid.Resources>
        <ItemsControl
         ItemsSource="{Binding Source={StaticResource dataResource}}"
         Width="Auto"
         Height="300">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border CornerRadius="5"
                            Background="Gainsboro"
                            Margin="5">
                     <StackPanel Margin="10,0,0,0">
                        <TextBlock Text="{Binding XPath=Name}"
                                   Margin="3"
                                   FontWeight="Bold"/>
                        <TextBlock Text="{Binding XPath=Price}"
                                   Margin="3"/>
                     </StackPanel>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>


Bu ilk ve basit senaryomuzdu.Veritabanımızda her oyun için bir For attribute’ımız var. Her oyunun hangi platform için olduğunu belirtiyor. Peki sadece PC uyumllu oyunları çekmek istersek nasıl yapabiliriz? Yapmamız gereken şey ItemsControl kontrolünün ItemsSource özelliğine xmldataprovider nesnesini geçirirken sorgu eklemek olacak. Bunu da şu aşağıdaki gibi yapabiliriz:

<Grid>
        <Grid.Resources>
            <XmlDataProvider x:Key="dataResource"
                             XPath="Games"
                             Source="GameData.xml"/>
        </Grid.Resources>
        <ItemsControl
            ItemsSource="{Binding Source={StaticResource dataResource},
            XPath=*[@For\=\'PS\']}"
                      Width="Auto"
                      Height="300">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border CornerRadius="5"
                            Background="Gainsboro"
                            Margin="5">
                     <StackPanel Margin="10,0,0,0">
                        <TextBlock Text="{Binding XPath=Name}"
                                   Margin="3"
                                   FontWeight="Bold"/>
                        <TextBlock Text="{Binding XPath=Price}"
                                   Margin="3"/>
                     </StackPanel>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>

Burada dikkat etmeniz gereken bir şey daha var. XmlDataProvider nesnemizdeki XPath=”Games/Game” sorgumuzu XPath=”Games” olarak değiştirdik. Çünkü sorgulama yaptığımız attribute sayesin hangi elementler üzerinde işlem yapacağı otomatik olarak tanımlanıyor. Sadece playstation için olan oyunları listelettiğimizde aşağıdaki ekran görüntüsüne sahip oluyoruz.
xmldataproviderwithquery

 Aşağıda örnek sorgu çeşitlerini bulabilirsiniz:
 ID’si 4’ten büyük ve PS için olan oyunlar *[@For\=\'PS\' and @ID\>\'4\']
 Hem PS için olan oyunları hem de ID’si 4 olan oyunu getirir *[@For\=\'PS\']|*[@ID\=\'4\']

10 Aralık 2015 Perşembe

Read an Excel File with JavaScript (without ActiveXObject)

  1. < script type = "text/javascript" > function Upload() {  
  2.     var fileUpload = document.getElementById("fileUpload");  
  3.     var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;  
  4.     if (regex.test(fileUpload.value.toLowerCase())) {  
  5.         if (typeof(FileReader) != "undefined") {  
  6.             var reader = new FileReader();  
  7.             reader.onload = function(e) {  
  8.                 var table = document.createElement("table");  
  9.                 var rows = e.target.result.split("\n");  
  10.                 for (var i = 0; i < rows.length; i++) {  
  11.                     var row = table.insertRow(-1);  
  12.                     var cells = rows[i].split(",");  
  13.                     for (var j = 0; j < cells.length; j++) {  
  14.                         var cell = row.insertCell(-1);  
  15.                         cell.innerHTML = cells[j];  
  16.                     }  
  17.                 }  
  18.                 var dvCSV = document.getElementById("dvCSV");  
  19.                 dvCSV.innerHTML = "";  
  20.                 dvCSV.appendChild(table);  
  21.             }  
  22.             reader.readAsText(fileUpload.files[0]);  
  23.         } else {  
  24.             alert("This browser does not support HTML5.");  
  25.         }  
  26.     } else {  
  27.         alert("Please upload a valid CSV file.");  
  28.     }  
  29. } < /script>  

Automatically Move Cursor to Next Field When TextBox is Full

  1. <html  
  2.     xmlns="http://www.w3.org/1999/xhtml">  
  3.     <head>  
  4.         <title>JavaScript to automatically move from one field to another field</title>  
  5.         <script type="text/javascript">  
  6. function movetoNext(current, nextFieldID) {  
  7. if (current.value.length >= current.maxLength) {  
  8. document.getElementById(nextFieldID).focus();  
  9. }  
  10. }  
  11. </script>  
  12.     </head>  
  13.     <body>  
  14.         <b>Enter your Text:</b>  
  15.         <input type="text" id="first" size="4" onkeyup="movetoNext(this, 'second')" maxlength="3" />  
  16.         <input type="text" id="second" size="4" onkeyup="movetoNext(this, 'third')" maxlength="3" />  
  17.         <input type="text" id="third" size="5" maxlength="4" />  
  18.     </body>  
  19. </html> 

Phone No (xxx-xxx-xxxx ) Validation in JQuery

  1. < script type = "text/javascript" >  
  2. //==================================  
  3. // xxx-xxx-xxxx Phnoe No Validation  
  4. //==================================  
  5. jQuery(document).ready(function() {  
  6.     $("#phone").keydown(function(e) {  
  7.         // Allow: backspace, delete, tab, escape, enter and .  
  8.         if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||  
  9.         // Allow: Ctrl+A  
  10.         (e.keyCode == 65 && e.ctrlKey === true) ||  
  11.         // Allow: home, end, left, right, down, up  
  12.         (e.keyCode >= 35 && e.keyCode <= 40)) {  
  13.             // let it happen, don't do anything  
  14.             return;  
  15.         }  
  16.         // Ensure that it is a number and stop the keypress  
  17.         if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {  
  18.             e.preventDefault();  
  19.         }  
  20.         var curchr = this.value.length;  
  21.         var curval = $(this).val();  
  22.         if (curchr == 3) {  
  23.             $("#phone").val(curval + "-");  
  24.         } else if (curchr == 7) {  
  25.             $("#phone").val(curval + "-");  
  26.         }  
  27.     });  
  28. }); < /script>  

Auto-Complete Input in HTML

  1. <input id="Input1" autocomplete="off" list="ListCountry" type="text" />  
  2. <datalist id="ListCountry">  
  3.     <option value='India'> </option>  
  4.     <option value='US'> </option>  
  5.     <option value='China'> </option>  
  6. </datalist> 

Convert JSON Data into HTML


  1. <div class="container">    
  2.     <p>    
  3.         <table id="placar" class="table table-condensed  table-bordered">    
  4.             <thead>    
  5.                 <tr>    
  6.                     <th>#</th>    
  7.                     <th>Name</th>    
  8.                     <th>K</th>    
  9.                     <th>D</th>    
  10.                     <th>Point</th>    
  11.                 </tr>    
  12.             </thead>    
  13.             <tbody></tbody>    
  14.         </table>    
  15. </div>  
Now as JSON for that Add below code in the JavaScript file:
  1. var data = [{    
  2.     'order''1',    
  3.         'name''Harshad',    
  4.         'k''3',    
  5.         'd''0',    
  6.         'score''121',    
  7.         'id''540'    
  8. }, {    
  9.     'order''2',    
  10.         'name''Rajesh',    
  11.         'k''15',    
  12.         'd''3',    
  13.         'score''122',    
  14.         'id''541'    
  15. }, {    
  16.     'order''3',    
  17.         'name''Bingo',    
  18.         'k''0',    
  19.         'd''23',    
  20.         'score''123',    
  21.         'id''542'    
  22. }];    
  23.     
  24. var currentID = 541;    
  25.     
  26. var transform = {    
  27.     tag: 'tr',    
  28.     children: [{    
  29.         "tag""td",    
  30.             "html""${order}"    
  31.     }, {    
  32.         "tag""td",    
  33.             "html""${name}"    
  34.     }, {    
  35.         "tag""td",    
  36.             "html""${k}"    
  37.     }, {    
  38.         "tag""td",    
  39.             "html""${d}"    
  40.     }, {    
  41.         "tag""td",    
  42.             "html""${score}"    
  43.     }]    
  44. };    
  45.     
  46. $('#placar > tbody ').json2html(data, transform);    
If you do the upar thing ur output is below: