Raw Sql Queries and Stored Procedure execution

Execute SQL query on existing entity

using (var context = new MyDBContext()) 
{ 
var posts = context.Posts.SqlQuery("SELECT * FROM dbo.Posts").ToList(); 
}

ToList() is mandatory here, otherwise query will not be executed, make sure you take care of sql injection attack if raw query is used

Execute Stored Procedure on existing entity

using (var context = new MyDBContext()) 
{ 
var posts = context.Posts.SqlQuery("dbo.spGetTopPosts").ToList(); 
}

 

ToList() is mandatory here, otherwise query will not be executed. Above code will execute Stored Procedure ‘spGetTopPosts’

Execute Stored Procedure with parameters on existing entity

using (var context = new MyDBContext()) 
{ 
var postID = 99; 
var posts = context.Posts.SqlQuery("dbo.spGetTopPosts @p0", postID).Single(); 
}

Single() is mandatory here, otherwise query will not be executed. Above code will execute Stored Procedure ‘spGetTopPosts’ with input paramter as postID

Execute SQL query on non-existing entity

using (var context = new MyDBContext()) 
{ 
var postTitles = context.Database.SqlQuery<string>("SELECT Title FROM dbo.Posts").ToList(); 
}

 

Execute SQL query by passing parameters

This is more better raw query as it avoid sql injections

using (var context = new MyDBContext()) 
{ 
var userSuppliedAuthor = new SqlParameter("@author", "Adi");
context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @author", userSuppliedAuthor);
}

Here the sql statement is executed on Posts table, so typeof(Post) is used. If a join statement is used on two different tables, then need to write an internal class for the returned values of sql statement.

Consider Posts, Category, Posts_Category tables exists. Posts_Category is mapping table of Posts – Id column and Category – Id column. If we want to execute sql join statement use the below code

internal class MappingData
{
public string CategoryTitle { get; set; }
public string PostTitle { get; set; }
public long? MappingId { get; set; }
}

using (var context = new MyDBContext())
{
var userSuppliedId = new SqlParameter("@PostId", PostID);
string sqlQuery = @"select c.Name CategoryTitle, pcm.Id MappingId, p.Title PostTitle from Posts_Categories pcm 
join Categories c on pcm.CategoryId = c.Id
join Posts p on pcm.PostId = p.Id where pcm.PostId =@PostId";
var Results = db.Database.SqlQuery<MappingData>(sqlQuery,userSuppliedId).ToList();
}
Results will be list of Categories of the given Post

Execute update SQL statment on non-existing entity

using (var context = new MyDBContext()) 
{ 

context.Database.ExecuteSqlCommand( 
"UPDATE dbo.Posts SET Title = 'Updated Title' WHERE PostID = 99"); 
}
For better understanding, summary extract of the method ‘SqlQuery’

 

Generate class from database table

TableName alanına tablo adını girip class üretebilirsiniz.

declare @TableName sysname = 'TableName'

declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
select 
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId,
case typ.name 
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'string'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'float'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'string'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'string'
when 'real' then 'double'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'string'
when 'time' then 'TimeSpan'
when 'timestamp' then 'DateTime'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
end ColumnType,
case 
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
then '?' 
else '' 
end NullableSign
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result + '
}'

print @Result

 

C# İle Ping Atmak

Bu yazımda Csharpta herhangi web sitesinden her hangi bir bilgisayara nasıl ping atılacagını ve atıldıgını anlatmaya çalışacağım. Aslına bakarsanız bu olayı gerçekleştirmek sanıldıgı kadar zor değil, namespace’imize freamwork’un kütabanelerinden System.Net.NetworkInformation kütüphanesini eklemek bizim için yeterli olacaktır.
Namespace’imize System.Net.NetworkInformation kütüphanemizi ekledikten sonra button’umunuzun click eventine geliyoruz. Ve diyoruz ki;

protected void Button1_Click(object sender, EventArgs e)
{
Ping ping = new Ping();
PingReply DonenCevap = ping.Send(TextBox1.Text);
if (DonenCevap.Status == IPStatus.Success)
{
// server ip adresini verir.
Label1.Text += Donencevap.Address.ToString() + "<br/>";

//server cevap süresini ms cinsinden verir.
Label1.Text += Donencevap.RoundtripTime.ToString() + "<br/>";

//server ayayına başladıktan sonra geçen gün sayısını verir.
Label1.Text += Donencevap.Options.Ttl.ToString() + "<br/>";
}
else if (Donencevap.Status == IPStatus.TimedOut)
{
Label1.Text = ("Zaman Aşımına Uğradı.");
}
}

 

Bu kodlar sayesinde ping olayımızı gerçekleştirebiliyoruz. Teşekkürler bir dahaki yazımda görüşmek dileğiyle.

Overload Kavramı

Overload Kavramı

Bu Makaleyi Paylaşın|
İsimleri aynı ancak dışarıdan aldığı parametrelerin pirimitiv tipleri farklı olan iki ayrı method yada fonksiyon tanımlama işlemine Overloading denir. Bir örnek vericek olursak.

using System;
class OguzhanABALI
{
public static void Main()
{
OguzhanABALI test = new OguzhanABALI();
Console.WriteLine(test.TestMethod("İlk Methodu Çağırıyorum"));
Console.WriteLine(test.TestMethod(6));
Console.ReadLine();
}
public String TestMethod(String newMesaj)
{
String mesaj = "String deger alan Methodhodu çağırdınız =" + newMesaj;
return mesaj;
}
public String TestMethod(int sayi)
{
String mesaj = "Integer deger alan Methodhodu çağırdınız =" + sayi;
return mesaj;
}
}

 

Görüldüğü gibi iki methodun da isimleri ve return tipleri aynı olmasına rağmen dışarıdan aldığı parametre tipleri farklı olduğu için istediğimiz methodu yada fonksiyonu çağırabildik.
Bir dahaki makalemde görüşmek üzere..Herkese iyi çalışmalar!