Mvc ve SignalR İle Hatırlatıcı Notlar Bölüm2
Selamlar;
Bugünkü makalede ilk bölümde anlattığımız projemize SignalR socket teknolojisini ekleyerek neler yapabileceğimize hep beraber inceleyeceğiz. Daha sonra da Azure’a publish edip herkesin kullanımına açacağız. Öncelikle signaR için aşağıdaki paketler NuGet’den indirilir.
İlk olarak sayfaya yeni bir note iliştirdiğimizde ilgili note’un o an sayfada olan tüm cilentlar için gözükmesini sağlayalım. Öncelikle bu işlemin yapılabilmesi için, ekleyen kişinin bu işlemden çıkarılması gerekir. Çünkü ilgili kişide note zaten gözükmektedir. Bunun için note’u ekleyen client’ın “connectionID”‘sinin alınıp “exclude” edilmesi gerekmektedir.
1-) Reciver adında bir signalR sınıfı yaratılır. “OnConnected()” methodunda ilgili client’ın “ConnectionID”‘si alınıp geri döndürülür. Aşağıdaki kodda “Caller“, online olan tek bir client’ı temsil etmektedir. “GetConnectionID()” client-side tarafta çalışan client’ın connectionID’sini alan bir functiondır.
HomeController.cs/(Reciver): “Context.ConnectionID” o an connect olan client’ın ConnectionID’sini bize verir.
1 2 3 4 5 6 7 |
public class Reciver:Hub { public override async Task OnConnected() { await Clients.Caller.GetConnectionID(Context.ConnectionId); } } |
2-)Client side tarafta Index.cshtml sayfasına ilgili javascript kütüpahaneleri aşağıdaki sırada eklenir. Dikkat edilir ise “jquery” kütüpahanesi, “signalR”‘dan önce sayfaya konulmuştur. Burdan da anlaşılacağı gibi signalR, Jquery kütüphanesini kullanmaktadır.
1 2 3 4 |
<script src="~/Scripts/jquery-2.1.4.min.js"></script> <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="@Url.Content("~/signalr/hubs")"></script> |
3-)Aşağıda görüldüğü gibi öncelikle signalR “reciver” hub class’ına connect olunmuş ve “GetConnectionID()” function’ı ile ilgili connectionID alınmıştır.
Index.cshtml/GetConnectionID:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> var hubProxy = $.connection.reciver; $.connection.hub.logging = true; $.connection.hub.start().done(function () { console.log("hub.start.done"); }).fail(function (error) { console.log(error); }); var connectionID; hubProxy.client.GetConnectionID = function (_connectionID) { console.log("ConnectionID:" + _connectionID); connectionID = _connectionID; } </script> |
Şimdi sıra geldi yeni bir note eklendiğinde tetiklenen “AddNote()” function’ını ve post ettiği “/Home/PostMessage” action’ını değiştirmeye.
AddNote() function’ına aşağıda görüldüğü gibi bize ait olan”ConnectionID” parametresi de eklenerek “PostMessage()” methodun’a gönderilir. ConnectionID’nin de gönderilmesinde amaç notu ekleyen yani biz hariç diğer clientlarda ilgili note’un gösterilmesidir.
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 |
function AddNote(id) { switch (id) { case 1: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'red', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 2: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'yellow', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 3: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'blue', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 4: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'green', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } } |
4-)Şimdi sıra geldi “PostMessage()” methodunda yapılması gereken değişikliğe. Aşağıda görüldüğü gibi ilgili “Reciver” signalR Hub classına asenkron olarak connect olunup “AddNote()” methodu “imgName” ve “ConnectionID” parametreleri ile birlikte trigger edilir.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("AddNote", imgName.ToString(), ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("AddNote", imgName.ToString(), ConnectionID); } |
HomeCotroller.cs/PostMessage(): Son hali aşağıdaki gibidir.
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 |
public async Task<string> PostMessage(string Note, string color,string ConnectionID) { Bitmap bmp = new Bitmap(Server.MapPath("/papers/" + color + ".png")); RectangleF rectf; if (color != "yellow") rectf = new RectangleF(40, 40, 200, 300); else rectf = new RectangleF(50, 60, 300, 300); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; if (color == "red") g.DrawString(Note, new Font("Comic Sans MS", 18, FontStyle.Bold), Brushes.White, rectf); else if (color == "yellow") g.DrawString(Note, new Font("Comic Sans MS", 31, FontStyle.Bold), Brushes.Red, rectf); else if (color == "green") g.DrawString(Note, new Font("Comic Sans MS", 35, FontStyle.Bold), Brushes.Blue, rectf); else if (color == "blue") g.DrawString(Note, new Font("Comic Sans MS", 18, FontStyle.Bold), Brushes.Black, rectf); g.Flush(); Guid imgName = Guid.NewGuid(); bmp.Save(Server.MapPath("/notes/" + imgName + ".png")); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); //HubConnection hubConnection = new HubConnection(" http://stickypaper.azurewebsites.net/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("AddNote", imgName.ToString(), ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("AddNote", imgName.ToString(), ConnectionID); } return imgName.ToString(); } |
5-)Şimdi sıra geldi ilgili signalR “Reciver” hub classında “AddNote()” methodunu oluşturmaya: Aşağıda görüldüğü gibi notu ekleyen client hariç diğer tüm clientlardaki, “AddNote()” function’ı, yeni oluşturulan image ismi ile birlikte tetiklenmektedir. “AllExcept()” methodunda note’u ekleyen client’ın ConnectionID ‘si verilerek kendisinin bu işlemden hariç tutulması, böylece kendisine aynı note’un 2. kere gösterilmesi engellenmiştir.
1 2 3 4 5 6 7 8 9 10 11 |
public class Reciver:Hub { public override async Task OnConnected() { await Clients.Caller.GetConnectionID(Context.ConnectionId); } public async Task AddNote(string imgName,string ConnectionID) { await Clients.AllExcept(ConnectionID).AddNote(imgName); } } |
6-)Şimdi sıra geldi tetiklenen client side taraftaki “AddNote()” functionını kodlamaya. Aşağıda görüldüğü gibi gelen image, ismine göre “draggable” divinin içine eklenir. Önemli bir konu da hareket ettirilebilmesi için style’ına “position:absolute” verilmesidir.
1 2 3 4 |
hubProxy.client.AddNote = function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }; |
init(): Function’ı önceki makalede de anlatıldığı gibi resimlerin sürüklenmesinden sonra kordinatlarının isminin sonuna eklenerek değiştirilmesini sağlar. Ayrıca resme çift tıklanması durumunda “DeleteImage()” methoduna post işlemi yaparak silinmesini sağlar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function init() { $(".paper").draggable({ start: function () { //coordinates(this); }, stop: function () { var _left = $(this)[0].style.left.replace("px", ""); var _top = $(this)[0].style.top.replace("px", ""); var left = _left; var top = _top; coordinates(top, left, this.src); } }); $(".paper").dblclick(function () { $.post("/Home/DeleteImage", { imgUrl: this.src, ConnectionID: connectionID }).done(function (imgName) { var object = $('img[src*="' + imgName + '"]'); object[0].remove(); }); }); } |
Şimdi sıra geldi silme işleminde bunu tüm clientlara duyurmaya. Aşağıdaki kod önceki makalede bahsettiğimiz “DeleteImage()” methodunun sonuna eklenir. “HubConnection” ile signalR sınıfının bulunduğu http yolu tanımlanır. Burdan da anlaşılacağı gibi signalR sınıfına bir servis gibi dışarıdan erişilmektedir. Bunun için “Microsoft.AspNet.SignalR.Client” kütüpahanesi kullanılır. “IHubProxy” ile signalR sınıfı olan “Reciver“‘a erişilir. Son olarak connect olunduktan sonra “Invoke” ile “DeleteImage()” methodu tetiklenir. Connect işlemi asenkron olduğu için “DeleteMethod()“‘u da asenkron hale getirilmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("DeleteImage", fileName, ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("DeleteImage", fileName, ConnectionID); } |
HomeController.cs/DeleteImage(): Aşağıda sil methodunun tam hali gözükmektedir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public async Task<string> DeleteImage(string imgUrl,string ConnectionID) { string fileName = Path.GetFileName(imgUrl); FileInfo file = new FileInfo(Server.MapPath("/Notes/" + fileName)); file.Delete(); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("DeleteImage", fileName, ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("DeleteImage", fileName, ConnectionID); } //---------------------------- return fileName; } |
Yeni bir note yaratma ve silme işlemlerinin, tüm clientlarda da gerçekleşmesi için signalR web socket teknolojisini var olan kodlara hepberaber ekledik.. Şimdi sıra geldi bir note’u hareket ettirdiğimizde, bunun tüm clientlarda gerçekleşmesini sağalamaya.
Önceki makaleden hatırlayacağımız gibi herhangi bir note’u hareket ettirdiğimizde: “Coordinate()” function’ı call edilmekte ve “ChangeImageName()” methoduna post işlemi yapılmaktadır.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var coordinates = function (_top, _left, src) { var name = src; console.log(src); var top = _top; var left = _left; console.log("top:" + top + " left:" + left); $.post("/Home/ChangeImageName", { Name: name, Cordinates: top + "x" + left, ConnectionID: connectionID }).done(function (newSrc) { var _newSrc = newSrc.split('æ')[0]; var _name = newSrc.split('æ')[1]; var object = $('img[src*="' + _name + '"]'); object[0].src = "http://localhost:34544/Notes/" + _newSrc; }); } |
ChangeImageName(): Aşağıda görüldüğü gibi Note’un ismi değiştirildikten sonra “Reciver” signalR sınıfına bağlanılıp “MovePaper()” methodu tetiklenmiştir. Parametre olarak, note’un sürüklenmedene sonraki yeni adı ve eski adı “æ” ayracı ile birleştirilerek, kordinatları “x” ayracı ile birleştirilerek ve son olarak ConnectionID’si gönderilmiştir.
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 |
public async Task<string> ChangeImageName(string Name, string Cordinates,string ConnectionID) { string NewName = Path.GetFileNameWithoutExtension(Name); FileInfo fInfo = new FileInfo(Server.MapPath("/Notes/"+NewName+".png")); if (NewName.Contains('_')) { NewName = NewName.Split('_')[0] + "_" + Cordinates+".png"; } else { NewName = NewName + "_" + Cordinates+".png"; } fInfo.MoveTo(Server.MapPath("/Notes/" + NewName)); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("MovePaper", (NewName + "æ" + Path.GetFileNameWithoutExtension(Name)), Cordinates, ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("MovePaper", (NewName + "æ" + Path.GetFileNameWithoutExtension(Name)), Cordinates, ConnectionID); } //---------------------------- return NewName+"æ"+Path.GetFileNameWithoutExtension(Name); } |
Reciver/MovePaper(): Aşağıda görüldüğü gibi işlemi yapan client haricinde(AllExcep()) methodu ile diğer tüm clientlardaki “MovePaper()” function’ı ilgili parametreler ile tetiklenir.
1 2 3 4 |
public async Task MovePaper(string newName,string Cordinates,string ConnectionID) { await Clients.AllExcept(ConnectionID).MovePaper(newName, Cordinates); } |
Index.cshtml/MovePaper(): Aşağıda görüldüğü gibi “top ve left” kordinatları “split” ile ayrıldıktan sonra aynı işlem eski ve yeni kordinatlar için yapılmıştır. Daha sonra hareket ettirilecek image eski “src” değerine göre jquery ile bulunmuştur. Son olarak yeni “src” değeri atanıp “animate()” function’ı ile yeni kordinat değerlerine animatif olarak hareket ettirilmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
hubProxy.client.MovePaper = function (newSrc, Cordinates) { var _top = Cordinates.split('x')[0]; var _left = Cordinates.split('x')[1]; var _newSrc = newSrc.split('æ')[0]; var _name = newSrc.split('æ')[1]; var object = $('img[src*="' + _name + '"]'); object[0].src = "http://localhost:34544/Notes/" + _newSrc; $(object[0]).clearQueue(); $(object[0]).stop(); $(object[0]).animate({ top: _top, left: _left }, 1000); }; |
Son olarak uygulama Azure üzerinde:(İptal)
http://stickypaper.azurewebsites.net/ adresine publish edilmiştir. Bu makalede yazdığımız bir yazıyı seçtiğimiz renkteki bir note’a iliştirip resme çevirdik. Daha sonra signalR web socket teknolojisi kullanılarak ilgili resim tüm clientlarda real time olarak oluşturuldu. Hatırlatıcı note hareket ettirildiğinde, yeni kordinatları ile ilgili resmin yolu değişirildi. Daha sonra signalR ile işlemi yapan client haricindeki tüm clientlarda da aynı function yeni kordinatlar ile tetiklenir ve note animatif olarak hareket ettirildi. Son olarak çift tıklanan resim, serverdan ve tüm client ekranlarından signalR web socket teknolojisi kullanılarak kaldırıldı ve sunucudan silindi.
Geldik bir makalenin daha sonuna. Yeni bir makalede görüşmek üzere hoşçakalın.
Source Code: http://www.borakasmer.com/projects/Reminder.rar
Index.cshtml(Full):
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-2.1.4.min.js"></script> <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var hubProxy = $.connection.reciver; $.connection.hub.logging = true; $.connection.hub.start().done(function () { console.log("hub.start.done"); }).fail(function (error) { console.log(error); }); var connectionID; hubProxy.client.GetConnectionID = function (_connectionID) { console.log("ConnectionID:" + _connectionID); connectionID = _connectionID; } hubProxy.client.MovePaper = function (newSrc, Cordinates) { var _top = Cordinates.split('x')[0]; var _left = Cordinates.split('x')[1]; var _newSrc = newSrc.split('æ')[0]; var _name = newSrc.split('æ')[1]; var object = $('img[src*="' + _name + '"]'); object[0].src = "http://localhost:34544/Notes/" + _newSrc; //object[0].src = "http://stickypaper.azurewebsites.net/Notes/" + _newSrc; $(object[0]).clearQueue(); $(object[0]).stop(); $(object[0]).animate({ top: _top, left: _left }, 1000); }; hubProxy.client.AddNote = function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }; hubProxy.client.DeleteImage = function (imgName) { var object = $('img[src*="' + imgName + '"]'); object[0].remove(); }; function init() { $(".paper").draggable({ start: function () { //coordinates(this); }, stop: function () { var _left = $(this)[0].style.left.replace("px", ""); var _top = $(this)[0].style.top.replace("px", ""); var left = _left; var top = _top; coordinates(top, left, this.src); } }); $(".paper").dblclick(function () { $.post("/Home/DeleteImage", { imgUrl: this.src, ConnectionID: connectionID }).done(function (imgName) { var object = $('img[src*="' + imgName + '"]'); object[0].remove(); }); }); } function AddNote(id) { switch (id) { case 1: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'red', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 2: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'yellow', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 3: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'blue', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } case 4: { $.post("/Home/PostMessage", { Note: $('#txtNote').val(), color: 'green', ConnectionID: connectionID }).done(function (imgName) { $('#draggable').append("<img src='/Notes/" + imgName + ".png' class='paper' style='position:absolute'/>"); init(); }); break; } } $("#txtNote").val(""); $("#txtNote").focus(); } $(document).ready(function () { $('#txtNote').focus(function () { if ($('#txtNote').val().trim() == 'Yazmak İstediğiniz Notu Belirtiniz!') { $('#txtNote').val(''); } }).blur(function () { if ($('#txtNote').val().trim() == '') { $('#txtNote').val('Yazmak İstediğiniz Notu Belirtiniz!') } }); $.ajax({ url: '/Home/GetImages', type: 'post', dataType: 'json', success: function (imageList) { for (var i = 0; i < imageList.length; i++) { if (imageList[i].ImageName.split('_').length > 1) { var _top = imageList[i].ImageName.split('_')[1].split('x')[0]; var _left = imageList[i].ImageName.split('_')[1].split('x')[1].replace('.png', ''); $('#draggable').append("<img src='/Notes/" + imageList[i].ImageName + "' class='paper' style='top:" + _top + "px; left: " + _left + "px; position:absolute'/>"); } else { $('#draggable').append("<img src='/Notes/" + imageList[i].ImageName + "' class='paper' style='position:absolute' />"); } }; init(); } }); }); var coordinates = function (_top, _left, src) { var name = src; console.log(src); var top = _top; var left = _left; console.log("top:" + top + " left:" + left); $.post("/Home/ChangeImageName", { Name: name, Cordinates: top + "x" + left, ConnectionID: connectionID }).done(function (newSrc) { var _newSrc = newSrc.split('æ')[0]; var _name = newSrc.split('æ')[1]; var object = $('img[src*="' + _name + '"]'); object[0].src = "http://localhost:34544/Notes/" + _newSrc; //object[0].src = "http://stickypaper.azurewebsites.net/Notes/" + _newSrc; }); } </script> <style> img.paper { width: 150px; height: 150px; padding: 0.5em; } img.menu { width: 50px; height: 50px; padding: 0.5em; } </style> </head> <body> <div id="container"> <div id="menu" style="background-image: url('/Menu/Background2.png');height:70px; z-index:999999"> <img src="~/Menu/MenuRed.png" class="menu" onclick="AddNote(1)" /> <img src="~/Menu/MenuYellow.png" class="menu" onclick="AddNote(2)" /> <img src="~/Menu/MenuBlue.png" class="menu" onclick="AddNote(3)" /> <img src="~/Menu/MenuGreen.png" class="menu" onclick="AddNote(4)" /> <textarea rows="3" cols="30" id="txtNote" style="font-size:medium; color:cornflowerblue;font-family:'Times New Roman';">Yazmak İstediğiniz Notu Belirtiniz!</textarea> </div> <br /> <div id="draggable" </div> </div> <script> init(); </script> </body> </html> |
HomeController.cs(Full):
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 162 163 |
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Client; using Microsoft.AspNet.SignalR.Client.Transports; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Reminder.Controllers { class Images { public string ImageName { get; set; } } public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public JsonResult GetImages() { DirectoryInfo directory = new DirectoryInfo(Server.MapPath("/Notes")); List<Images> ImageList = new List<Images>(); foreach (FileInfo file in directory.GetFiles().OrderBy(img=>img.CreationTime)) { Images img = new Images(); img.ImageName = file.Name; ImageList.Add(img); } return Json(ImageList, JsonRequestBehavior.AllowGet); } public async Task<string> DeleteImage(string imgUrl,string ConnectionID) { string fileName = Path.GetFileName(imgUrl); FileInfo file = new FileInfo(Server.MapPath("/Notes/" + fileName)); file.Delete(); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); //HubConnection hubConnection = new HubConnection(" http://stickypaper.azurewebsites.net/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("DeleteImage", fileName, ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("DeleteImage", fileName, ConnectionID); } //---------------------------- return fileName; } public async Task<string> ChangeImageName(string Name, string Cordinates,string ConnectionID) { string NewName = Path.GetFileNameWithoutExtension(Name); FileInfo fInfo = new FileInfo(Server.MapPath("/Notes/"+NewName+".png")); if (NewName.Contains('_')) { NewName = NewName.Split('_')[0] + "_" + Cordinates+".png"; } else { NewName = NewName + "_" + Cordinates+".png"; } fInfo.MoveTo(Server.MapPath("/Notes/" + NewName)); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); //HubConnection hubConnection = new HubConnection(" http://stickypaper.azurewebsites.net/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("MovePaper", (NewName + "æ" + Path.GetFileNameWithoutExtension(Name)), Cordinates, ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("MovePaper", (NewName + "æ" + Path.GetFileNameWithoutExtension(Name)), Cordinates, ConnectionID); } //---------------------------- return NewName+"æ"+Path.GetFileNameWithoutExtension(Name); } public async Task<string> PostMessage(string Note, string color,string ConnectionID) { Bitmap bmp = new Bitmap(Server.MapPath("/papers/" + color + ".png")); RectangleF rectf; if (color != "yellow") rectf = new RectangleF(40, 40, 200, 300); else rectf = new RectangleF(50, 60, 300, 300); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; if (color == "red") g.DrawString(Note, new Font("Comic Sans MS", 18, FontStyle.Bold), Brushes.White, rectf); else if (color == "yellow") g.DrawString(Note, new Font("Comic Sans MS", 31, FontStyle.Bold), Brushes.Red, rectf); else if (color == "green") g.DrawString(Note, new Font("Comic Sans MS", 35, FontStyle.Bold), Brushes.Blue, rectf); else if (color == "blue") g.DrawString(Note, new Font("Comic Sans MS", 18, FontStyle.Bold), Brushes.Black, rectf); g.Flush(); Guid imgName = Guid.NewGuid(); bmp.Save(Server.MapPath("/notes/" + imgName + ".png")); //Triger SignalR if (Session["hubProxy"] == null) { HubConnection hubConnection = new HubConnection("http://localhost:34544/"); //HubConnection hubConnection = new HubConnection(" http://stickypaper.azurewebsites.net/"); IHubProxy hubProxy = hubConnection.CreateHubProxy("Reciver"); await hubConnection.Start(new LongPollingTransport()); Session.Add("hubProxy", hubProxy); hubProxy.Invoke("AddNote", imgName.ToString(), ConnectionID); } else { ((IHubProxy)Session["hubProxy"]).Invoke("AddNote", imgName.ToString(), ConnectionID); } return imgName.ToString(); } } public class Reciver:Hub { public override async Task OnConnected() { await Clients.Caller.GetConnectionID(Context.ConnectionId); } public async Task MovePaper(string newName,string Cordinates,string ConnectionID) { await Clients.AllExcept(ConnectionID).MovePaper(newName, Cordinates); } public async Task AddNote(string imgName,string ConnectionID) { await Clients.AllExcept(ConnectionID).AddNote(imgName); } public async Task DeleteImage(string imgName, string ConnectionID) { await Clients.AllExcept(ConnectionID).DeleteImage(imgName); } } } |
Source:
- https://stackoverflow.com/questions/6826921/write-text-on-an-image-in-c-sharp
- https://stackoverflow.com/questions/6311545/c-sharp-write-text-on-bitmap/6311628
- https://stackoverflow.com/questions/21431879/jquery-drag-to-get-start-and-stop-coordinates
- https://stackoverflow.com/questions/849030/how-do-i-get-the-coordinate-position-after-using-jquery-drag-and-drop
Visual Studio 2013 altında kodları aynen aldım. Ama “The type or namespace name ‘Hub’ could not be found (are you missing a using directive or an assembly reference?)” hatası veriyor.
Dosyalarını paylaşma durumunuz var mı?
Tabiki…Nuget’den signalR paketlerini indirdin mi?
Bir de sayfanın yukarısına alttaki kütüphaneleri eklemen gerekiyor…
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Transports;
Teşekkürler hocam, başarılar dilerim.