AngularJS Altında SignalR Çalıştırma Webinar Etkinliği Bölüm 2
Selamlar ;
Öncelikle webinar’a katılan tüm arkadaşlara teşekkür ederim. Umarım sizin için faydalı olmuştur. Eğer AngularJS ve SignalR hakkında bir nebze olsun aklınızda fikirler oluşturabilmiş isem bu webinar amacına ulaşmıştır.
Bu bölümde Webinar’ın 1.Bölümünde üzerinde işlem yaptığımız product’ları editlemeye çalıştık. Tabi bu sırada diğer clientların editlenecek product’ı değiştirmemesi için ilgili ürünü lockladık. Yani edit ve delete buttonlarını gizledik. Ama product’ı değiştiricek user için farklı bir davranış sergileyerek edit textbox’ları ve update buttonlarını gösterip ilgili product’ın price ve ProductName fieldlarını gizledik. Böylece user’a göre signalR’da nasıl farklı işlemlar yaptığımızı gördük. Bunun haricinde angularJs’in ilginize çekebilecek birkaç özelliğini, örnekler eşliğinde inceledik. Bizden json data bekleyen PostProduct adında bir action servis hazırladık. İçini products’ların json formatında doldurduğumuz textarea’mızın value’sunu $http.post ile bu servise gönderdik. Böylece $700 dolardan fazla olan ürünlerini sayısını bulduk. AngularJS filter üzerine çeşitli örnekler yaptık. Checkbox’a göre filitreleme işleminde bulunduk. Add button’una koşul koyarak product sayısı 6’dan fazla ise gözükmemesini sağladık. Kısaca 6’dan fazla ürün girişine izin vermedik. Loading işleminde yükleniyor sembolü çıkardık. ProductPrice’da currency filter üzerine konuştuk.
Source kodlar ve ilgili birkaç ekran görüntüsü aşağıdadır.
Bir sonraki event’de görüşmek üzere herkese hoşçakalın.
HomeController.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using Microsoft.AspNet.SignalR; using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Web; using System.Web.Mvc; using DAL; namespace Signalr_AngularJs.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public string PostProduct(List<Products> listProducts) { int resultCount = 0; foreach (Products product in listProducts) { if (product.Price > 700) { resultCount++; } } return "Toplam [" + listProducts.Count.ToString() + "] adet ürünün içinden [" + resultCount.ToString() + "] adedi $700'da büyüktür."; } } public class ProductHub:Hub { public static ConcurrentDictionary<string, int> listLock = new ConcurrentDictionary<string, int>(); public static object _lockObject = new object(); public static HepsioradaContext db = new HepsioradaContext(); public override async System.Threading.Tasks.Task OnConnected() { var productList = from prod in db.Products orderby prod.ProductName select prod; await Clients.Caller.getAllProducts(productList); await Clients.All.lockAll(listLock.Values); } public override async System.Threading.Tasks.Task OnDisconnected(bool stopCalled) { int removeID; listLock.TryRemove(Context.ConnectionId, out removeID); await Clients.All.lockAll(listLock.Values); } public override async System.Threading.Tasks.Task OnReconnected() { await OnConnected(); } public void AddProduct(Products prod) { db.Products.Add(prod); db.SaveChanges(); Clients.All.addProduct(prod); } public void DeleteProduct(Products product) { var productItem = db.Products.SingleOrDefault(prod => prod.ID == product.ID); db.Products.Remove(productItem); db.SaveChanges(); Clients.All.deleteProduct(product); } public void allLock(Products product) { lock (_lockObject) { foreach (int productID in listLock.Values) { if (product.ID == productID) { return; } } listLock.AddOrUpdate(Context.ConnectionId, product.ID, (oldKey, oldValue) => product.ID); Clients.Caller.allLockSuccess(product); Clients.All.lockAll(listLock.Values); } } public void updateProduct(Products _product) { var product = db.Products.SingleOrDefault(prod => prod.ID == _product.ID); product.ProductName = _product.ProductName; product.Price = _product.Price; db.SaveChanges(); int removeID; listLock.TryRemove(Context.ConnectionId, out removeID); Clients.All.updateProduct(_product); Clients.All.lockAll(listLock.Values); } } } |
Index.cshtm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
@{ Layout = null; } <!DOCTYPE html> <html> <head> <script src="~/Scripts/angular.min.js"></script> <script src="~/Scripts/jquery-2.1.1.min.js"></script> <script src="~/Scripts/jquery.signalR-2.1.1.min.js"></script> <script src="/signalr/hubs"></script> <script> function Controller($scope, $http) { var hubProxy = $.connection.productHub; $scope.submit = function () { $http.post("http://localhost:7108/Home/PostProduct", $("#textProducts").val()).success(function (result) { alert(result); }); } $scope.addProduct = function () { hubProxy.server.addProduct($scope.add_product); $scope.add_product.ProductName = ""; $scope.add_product.Price = ""; } $scope.isLoad = true; $scope.delete = function (product) { hubProxy.server.deleteProduct(product); } $scope.edit = function (product) { hubProxy.server.allLock(product); } $scope.isEdit = function (product) { if ($scope.edit_product === undefined) { return false; } return $scope.edit_product.ID === product.ID; } $scope.update = function () { hubProxy.server.updateProduct($scope.edit_product); $scope.edit_product = undefined; } hubProxy.client.getAllProducts = function (products) { $scope.isLoad = true; console.log("client.getAllProducts " + JSON.stringify(products)); $scope.Products = products; setCheckArray($scope.Products); $scope.isLoad = false; $scope.$apply(); } hubProxy.client.addProduct = function (product) { $scope.isLoad = true; console.log("client.addProduct " + JSON.stringify(product)); $scope.Products.push(product); setCheckArray($scope.Products); $scope.isLoad = false; $scope.$apply(); } hubProxy.client.deleteProduct = function (product) { console.log("client.deleteProduct " + JSON.stringify(product)); removeItemById(product.ID, $scope.Products); $scope.$apply(); } hubProxy.client.allLockSuccess = function (product) { console.log("client.allLockSuccess " + JSON.stringify(product)); $scope.edit_product = product; $scope.$apply(); } hubProxy.client.lockAll = function (lockList) { for (var index = 0; index < $scope.Products.length; index++) { $scope.Products[index].isLocked = false; } for (var index2 = 0; index2 < lockList.length; index2++) { for (var index3 = 0; index3 < $scope.Products.length; index3++) { if ($scope.Products[index3].ID === lockList[index2]) { $scope.Products[index3].isLocked = true; break; } } } $scope.$apply(); } hubProxy.client.updateProduct=function(product) { console.log("client.updateProduct " + JSON.stringify(product)); updateProductById(product.ID, $scope.Products, product); setCheckArray($scope.Products); $scope.$apply(); } $.connection.hub.logging = true; $.connection.hub.start() .done(function () { console.log("client.hub.done"); }) .fail(function (error) { console.log(error); }); } function removeItemById(ID, Array) { for (var index = 0; index < Array.length; index++) { if (Array[index].ID === ID) { Array.splice(index, 1); } } } function setCheckArray(Array) { for (var index = 0; index < Array.length; index++) { Array[index].isChecked = index % 2 === 0 ? true : false; } } function updateProductById(ID, Array, product) { for (var index = 0; index < Array.length; index++) { if (Array[index].ID === ID) { Array[index] = product; } } } </script> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div ng-app="" ng-controller="Controller"> Filter : <input type="text" ng-model="searchText" /> | Filter Any: <input type="text" ng-model="searchText.$" /> | Filter Name: <input type="text" ng-model="searchText.ProductName" /> | Filter Price: <input type="text" ng-model="searchText.Price" /> | Filter Check: <input type="checkbox" ng-model="searchText.isChecked" /> <table> <tr> <th></th> <th></th> <th><a href="" ng-click="orderColomun='ID'">ID</a></th> <th><a href="" ng-click="orderColomun='ProductName'">Product Name</a></th> <th><a href="" ng-click="orderColomun='Price'">Price</a></th> <th>Checked</th> </tr> <tr><td><img src="/loader.gif" ng-show="isLoad" /></td></tr> <tr ng-repeat="product in Products | orderBy:orderColomun | filter:searchText"> <td ng-show="!product.isLocked"><button ng-click="delete(product)">Delete</button></td> <td> <button ng-click="edit(product)" ng-show="!product.isLocked">Edit</button> <button ng-click="update()" ng-show="isEdit(product)">Update</button> </td> <td> {{ product.ID }} </td> <td ng-show="!isEdit(product)"> {{ product.ProductName }}</td> <td ng-show="isEdit(product)"><input type="text" ng-model="edit_product.ProductName" /></td> <td ng-show="!isEdit(product)"> {{ product.Price | currency:"$"}}</td> <td ng-show="isEdit(product)"><input type="text" ng-model="edit_product.Price" /></td> <td> {{ product.isChecked }}</td> </tr> <tr> <td></td> <td></td> <td ng-show="Products.length<6"><button ng-click="addProduct()">Add</button></td> <td><input type="text" ng-model="add_product.ProductName" /></text></td> <td><input type="text" ng-model="add_product.Price" /></text></td> </tr> </table> <button ng-click="submit()">Submit</button><br /> <textarea style="width:700px;height:500px" id="textProducts">{{ Products | json}}</textarea> </div> </body> </html> |
Source Code: http://www.borakasmer.com/projects/Signalr_AngularJs_Full.rar
Bora bey merhaba,
Controller dan veriyi JsonResult olarak dönüp Products a atamak mı yoksa “Products | json” bu şekilde mi daha performaslı olur.
Selamlar Ali;
2 yöntemi de big data ile denedim Products | json ile daha performanslı gözüküyor. Ama şunu belirtiyim dişe dokunur bir fark yok.
İyi çalışmalar.