Yazar: Tarık AKBAY

Bilgisayar Mühendisi

DHT-11 Sıcaklık ve Nem Sensörü (Temperature and Humidity sensor)

Tek dijital pin aracılığıyla sıcaklık ve nem verilerini sağlamaktadır.
Fakat kararlı sonuçlar alamadım.

Ölçüm aralığı:
Nem: 20 – 90%RH hassasiyet:±5%RH
Sıcaklık: 0-50 ℃ hassiyet:±2℃

Detaylı bilgi için dökümanı inceleyiniz. dht11

Arduinoda kullanmak için dht11 kütüphanesi indirin.
Arduino sketch->Include library->Manage libraries-> Library Manager->
dht sensor library 1.2.3

Devreyi aşağıda ki şekilde bağlıyoruz. Kütüphaneyle birlikte gelen örneği doğru bağlantı yapıldıysa serial monitor aracılığıyla sıcaklık ve nem bilgisi okursunuz.

Kullanılan malzemeler:
10 k direnç
dht11 sensör

elementz_dht11_bb

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what digital pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

HandleErrorAttribute Customize Request Ajax

 

public override void OnException(ExceptionContext filterContext)
{
	var controllerName = filterContext.RouteData.Values["controller"];
	var actionName = filterContext.RouteData.Values["action"];
	var userName = HttpContext.Current.User.Identity.Name;
	var area = filterContext.RouteData.DataTokens["area"];

	if (filterContext.HttpContext.Request.IsAjaxRequest())
	{
		filterContext.ExceptionHandled = true;

		filterContext.HttpContext.Response.Clear();
		filterContext.HttpContext.Response.StatusCode = Convert.ToInt32(System.Net.HttpStatusCode.InternalServerError);
		filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
		filterContext.Result = new JsonResult
		{
			Data = new { result = false, ExceptionMessage = filterContext.Exception.Message },
			JsonRequestBehavior = JsonRequestBehavior.AllowGet
		};
	}

	base.OnException(filterContext);
}

 

Asp.net MVC Razor Html Helper ile Captcha

Basit kullanımlı, basit bir captcha ihtiyacımı karşılamak için geliştirdiğim kod blokları aşağıda ki gibidir.

Razor olarak kullanmak için Html Extensions

    public static partial class HtmlExtensions
    {
        public static MvcHtmlString Captcha(this HtmlHelper helper)
        {
            string result = string.Empty;

            var panel = new TagBuilder("div");
            panel.Attributes.Add("class", "panel panel-default");

            var mainDiv = new TagBuilder("div");
            mainDiv.Attributes.Add("id", "captchaHtmlExtensions");
            mainDiv.Attributes.Add("ct-captcha", "");

            var imageDiv = new TagBuilder("div");
            imageDiv.Attributes.Add("id", "captchaImage");
            imageDiv.Attributes.Add("class", "col-md-12");
            imageDiv.Attributes.Add("onclick", "getCaptchaImage()");

            var input = new TagBuilder("input");
            input.Attributes.Add("name", "captchaValue");
            input.Attributes.Add("id", "captchaValue");
            input.Attributes.Add("class", "form-control");
            input.Attributes.Add("type", "form-text");
            input.Attributes.Add("placeholder", "Kodu Giriniz");

            var text = new TagBuilder("h6");
            text.InnerHtml = "Doğrulama Kodu";
            text.Attributes.Add("class", "panel-heading panel-title");

            panel.InnerHtml += text.ToString();
            panel.InnerHtml += mainDiv.ToString();
            panel.InnerHtml += imageDiv.ToString();
            panel.InnerHtml += input.ToString();

            result += panel.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(result);
        }
    }

base64 olarak geri dönen captcha image methodu:

        public static string GetCaptchaImageByBase64()
        {
            bool noisy = true;
            var random = new Random((int)DateTime.Now.Ticks);

            int imageWidth = 100;
            int imageHeight = 30;

            //generate text
            int length = 3;
            string characters = "ABCDEFGHIJKLMNOPRSTUVYZ";
            StringBuilder result = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                result.Append(characters[random.Next(characters.Length)]);
            }

            //generate text

            var captcha = result.ToString();

            //result
            HttpContext.Current.Session["CaptchaImageResult"] = result.ToString();

            //captchaImage

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(imageWidth, imageHeight))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 8; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (random.Next(0, 255)),
                        (random.Next(0, 255)),
                        (random.Next(0, 255)));

                        r = random.Next(0, (imageWidth / 3));
                        x = random.Next(0, imageWidth);
                        y = random.Next(0, imageHeight);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //image add text
                gfx.DrawString(captcha, new Font("Tahoma", 18), Brushes.Gray, 15, 3);

                //generate image stream
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Png);
                string srcValue = string.Format("data:image/png;base64, {0}", Convert.ToBase64String(mem.ToArray()));

                return srcValue;
            }
        }

Oluşan captcha image’nı json olarak döndüren method:

        public ActionResult GetCaptchaImageJson()
        {
            return Json(Operations.GetCaptchaImageByBase64(), JsonRequestBehavior.AllowGet);
        }

Javascript function:

$(document).ready(function () {
    $("div").each(function () {

        if ($(this).attr("ct-Captcha") != undefined) {
            getCaptchaImage();

            $("#captchaValue").bind('keyup', function (e) {
                if (e.which >= 97 && e.which <= 122) {
                    var newKey = e.which - 32;
                    e.keyCode = newKey;
                    e.charCode = newKey;
                }
                $("#captchaValue").val(($("#captchaValue").val()).toUpperCase());
            });
        }
    });
});
function getCaptchaImage() {
    $.ajax({
        cache: false,
        async: true, //!!!
        type: "POST",
        url: pureRoot + "Json/GetCaptchaImageJson",
        success: function (data) {
            //console.log(data, "UTIL -> getCaptchaImage -> success");
            $('#captchaImage').html('<div style="margin:5px;"><img src="' + data + '" class="img-responsive" title="Yenilemek için tıklayınız"/></div>')
            $("#captchaValue").val('');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log("Bağlantı sırasında hata oluştu!", "UTIL -> getCaptchaImage -> error");
        }
    });
}

Kullanımı:

@Html.Captcha()

Captcha

Ms Sql database ve tablo boyut bilgileri

--Tüm db lerin bellekteki sayfa sayılarının verir
SELECT database_id,DB_NAME(database_id),COUNT(*) "Bellekteki Sayfa Sayisi",
(COUNT(*)*8)/1024 AS "Bellekteki Sayfa Boyutu KB"
FROM sys.dm_os_buffer_descriptors
GROUP BY database_id

--Tablonun satır sayısı ve ne kadar yer tutuğu bilgisini verir
sp_spaceused ProductMovement

--databaseleri gösterir
select * from sys.databases

--Database dosyalarını gösterir
SELECT * FROM sys.database_files

--Database bilgilerini verir
sp_helpdb DATABASE_ISMI

--Sunucu üzerinde bağlantıları ve processlerini görmek için
sp_who2

--Tablonun object IDsini verir
SELECT OBJECT_ID('Brand')
-- ObjectID nin adını verir
SELECT OBJECT_NAME('2098106515')

--Tablosunun page'leri gösterir
DBCC IND(0,'Brand',1)

--Tablonun indexlerini gösterir
SELECT * FROM sys.indexes WHERE object_id=OBJECT_ID('Brand')

 

Mssql İzleme Komutları

--Top IO kullanan
SELECT TOP 10
creation_time
,       last_execution_time
,       total_logical_reads AS [LogicalReads]
,       total_logical_writes AS [LogicalWrites]
,       execution_count
,       total_logical_reads+total_logical_writes AS [AggIO]
,       (total_logical_reads+total_logical_writes)/(execution_count+0.0) AS [AvgIO]
,      st.TEXT
,       DB_NAME(st.dbid) AS database_name
,       st.objectid AS OBJECT_ID
FROM sys.dm_exec_query_stats  qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle) st
WHERE total_logical_reads+total_logical_writes > 0
AND sql_handle IS NOT NULL
ORDER BY [AggIO] DESC


--Top CPU kullanan
SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
--ORDER BY qs.total_logical_reads DESC -- logical reads
-- ORDER BY qs.total_logical_writes DESC -- logical writes
 ORDER BY qs.total_worker_time DESC -- CPU time

SELECT
allocated_page_file_id as PageFID
,allocated_page_page_id as PagePID
,allocated_page_iam_file_id as IAMFID
,allocated_page_iam_page_id as IAMPID
,object_id as ObjectID
,index_id as IndexID
,partition_id as PartitionNumber
,rowset_id as PartitionID
,allocation_unit_type_desc as iam_chain_type
,page_type as PageType
,page_type_desc as PageTypDesc
,page_level as IndexLevel
,next_page_file_id as NextPageFID
,next_page_page_id as NextPagePID
,previous_page_file_id as PrevPageFID
,previous_page_page_id as PrevPagePID
FROM sys.dm_db_database_page_allocations(DB_ID('VERITABANI_ISMI'), OBJECT_ID('COMPANY'), NULL, NULL, 'DETAILED')

SELECT allocated_page_page_id "Sayfa No",
extent_page_id "Extent Ýlk Sayfasý", 
allocated_page_iam_page_id,
is_allocated,
is_mixed_page_allocation,
page_type,
page_type_desc
FROM sys.dm_db_database_page_allocations(
	DB_ID('VERITABANI_ISMI'), OBJECT_ID('COMPANY'), NULL, NULL, 'DETAILED')

SELECT OBJECT_NAME(object_id), * FROM sys.dm_db_database_page_allocations(
DB_ID('VERITABANI_ISMI'), NULL, NULL, NULL, 'DETAILED')

--Tabloların kullanım boyutlarını verir
SELECT 
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    t.Name

 

Sql Server fragmentation

--Tablo indexlerinin dağılma oranı
--avg_fragmentation_in_percent alanı %5 ile %30 ise index reorganize edilir
--avg_fragmentation_in_percent alanı %30dan büyük ise index rebuild edilir
--Nasıl yapılır: tablo -> Indexes -> sağ tuş rebuild veye reorganize edilir
SELECT OBJECT_NAME(ps.OBJECT_ID),i.name, ps.index_id,index_type_desc,index_level,
avg_fragmentation_in_percent,avg_page_space_used_in_percent,page_count
FROM sys.dm_db_index_physical_stats
(DB_ID(N'TABLE_NAME'), NULL, NULL, NULL , 'SAMPLED') AS PS
INNER JOIN sys.indexes i on i.object_id = ps.object_id and i.index_id = ps.index_id
ORDER BY avg_fragmentation_in_percent DESC

 

Windows Service Kolay Debug

Projenin “Properties -> Application” sekmesinden “Output Type”‘ı Console Application olarak değiştirin.

ServiceDebug

“Program.cs” aşağıda ki şekilde güncelleyin.

static void Main()
{
    ServiceBase[] servicesToRun;
    servicesToRun = new ServiceBase[] 
    {
        new WindowsService()
    };

    if (Environment.UserInteractive)
    {
        RunInteractive(servicesToRun);
    }
    else
    {
        ServiceBase.Run(servicesToRun);
    }
}
private static void RunInteractive(ServiceBase[] servicesToRun)
{
    Console.WriteLine("Services running in interactive mode.");
    Console.WriteLine();

    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Starting {0}...", service.ServiceName);
        onStartMethod.Invoke(service, new object[] { new string[] { } });
        Console.Write("Started");
    }

    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine(
        "Press any key to stop the services and end the process...");
    Console.ReadKey();
    Console.WriteLine();

    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Stopping {0}...", service.ServiceName);
        onStopMethod.Invoke(service, null);
        Console.WriteLine("Stopped");
    }

    Console.WriteLine("All services stopped.");
    // Keep the console alive for a second to allow the user to see the message.
    Thread.Sleep(1000);
}

 

WCF KnownType Attribute

Aşağıda ki gibi bi class yapısında wcf Service Interface’nin de sadece person nesnesini belirttiğinizde, istemci tarafında student ve teacher nesnelerini göremeyeceksiniz. Bunun çözümü ise KnownType attribute ile yapılabilir.

[DataContract] 
public abstract class Person
	{
		[DataMember]
		public int Code { get; set; }
 
		[DataMember]
		public string Name { get; set; }
	}

[DataContract]  
public class Student : Person
	{
		[DataMember]
		public int StudentId { get; set; }
	}

[DataContract]
public class Teacher : Person
	{
		[DataMember]
		public int TeacherId { get; set; }
	}

Çözümü için farklı yöntemleri bulunmaktadır. Ben 2 farklı çözümünü belirtieceğim.

  • Abstract class üzerine knownType Attribute ekleyerek.
[DataContract]
 [KnownType( typeof( Student ) )]
 [KnownType( typeof(Teacher) )]
 public abstract class Person
 {
     [DataMember]
     public int Code { get; set; }
 
     [DataMember]
     public string Name { get; set; }
 }
  • Interface üzerine Helper yazarak
[ServiceKnownType("GetKnownTypes", typeof(Helper))]
[ServiceContract()]
public interface IShop
{
	[OperationContract]
	List<Person> GetPersonList();
}
static class Helper
{
	public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
	{
		knownTypes.Add(typeof(Student);
		knownTypes.Add(typeof(Teacher);
		return knownTypes;
	}
}

İstersek person classından türeyen her class için knownTypes listesini runtime oluşturabiliriz.

static class Helper
{
	public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
	{
		Assembly assembly = Assembly.GetAssembly(typeof(Person));
		List<Type> types = assembly.GetExportedTypes().Where(e => e.BaseType == typeof(SurrogateLibrary.Form)).ToList();

		return types;
	}
}

 

Kaynak:

https://msdn.microsoft.com/en-us/library/system.servicemodel.serviceknowntypeattribute.aspx