28 Ekim 2013 Pazartesi

SQL Server Count Alternative

SQL Server da count alırken yavaş sonuç alınıyorsa aşağıdaki sorgu kullanılabilir:

SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE OBJECT_NAME(OBJECT_ID) = N'CihazVeri'

14 Haziran 2013 Cuma

Javascript ile session kullanımı

ASP.NET uygulamalarında javascript ile session bilgilerine erişim (okuma yada yazma) Generic Handler (.ashx) kullanılabilir. Burada önemli olan IRequiresSessionState arayüzünün handler'a uygulanmasıdır. Örnekde kullanılacak handler aşağıdaki gibidir:

public class SessionHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
           
            string key = context.Request.QueryString["key"];
            string method = context.Request.QueryString["method"];
            string value = context.Request.QueryString["value"];

            if (method.ToLower() == "post")
            {
                context.Session[key] = value;
                context.Response.Write("ok");
            }

            if (method.ToLower() == "get")
            {
                context.Response.Write(context.Session[key]);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Handler oluşturulduktan sonra artık herhangi bir sayfadan aşağıdaki şekilde bu handler çağrılabilir.
<script src="Scripts/jquery-1.8.2.min.js"></script>
<input type="button" value="Set Session" onclick="fnSetSession()" />

    <input type="button" value="Get Session" onclick="fnGetSession()" />

    <script type="text/javascript">

        function fnGetSession() {
            $.ajax({
                url: "/SessionHandler.ashx?method=get&key=kullanici",
                contentType: "text/plain; charset=utf-8",
                success: function (data) {
                    alert(data);
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }

        function fnSetSession() {
            $.ajax({
                url: "/SessionHandler.ashx?method=post&key=kullanici&value=erdem_bener",
                contentType: "text/plain; charset=utf-8",
                success: function (data) {
                    alert(data);
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }
</script>


31 Mayıs 2013 Cuma

Application Initialization UI for IIS 7.5

IIS 7.5 için Application Initialization Module hakkında bilgi için;
http://www.iis.net/downloads/microsoft/application-initialization

IIS 7.5 de Application Initialization ayarlarının yapılması için aşağıdaki adresten indirelecek uygulama kurulduktan sonra IIS Managerda Application Initialization ayarları görünecektir.

ApplicationInitializationUIInstaller_x64.zip

Aşağıdaki şekilde  IIS de gerekli ayarlar yapıldıktan sonra Initialization Module ile ilgili ayarlar tamamlanmış olacaktır.


 

18 Şubat 2013 Pazartesi

String To MD5 Extension



giriş stringini büyük yada küçük harf olarak MD5 e çevirir

[System.Diagnostics.DebuggerStepThrough]
public static string xToMD5(string giris, bool? buyukHarf)
{
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(giris);
byte[] hashBytes = md5.ComputeHash(inputBytes);

StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
if (buyukHarf == null || buyukHarf.Value == false)
sb.Append(hashBytes[i].ToString("x2"));
else
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}

15 Ocak 2013 Salı

SQL'i en çok yoran sorgular

select top 100 substring
(
    b.text, (a.statement_start_offset/2) + 1,
    (
        (
            case statement_end_offset when -1 then datalength(b.text) else a.statement_end_offset end - a.statement_start_offset
        ) / 2
    ) + 1
) as statement_text,
c.query_plan,total_worker_time as cpu_time,execution_count,total_physical_reads,total_logical_reads,total_elapsed_time,last_elapsed_time,max_elapsed_time,min_elapsed_time
from sys.dm_exec_query_stats a
cross apply sys.dm_exec_sql_text (a.sql_handle) as b
cross apply sys.dm_exec_query_plan (a.plan_handle) as c
order by total_worker_time desc

2 Ocak 2013 Çarşamba

Unique Computer ID (FingerPrint)

Yapılan uygulamaların lisanslaması için kullanılabilecek ve her bilgisayara özel oluşturulacak key ile ilgili yardımcı bir sınıf. Temel olarak Anakart, BIOS, CPU, Disk, MACID kullanılabilmekte. Ben Anakarti BIOS ve CPU ID lerinin kullanılarak sonuca ulaşılmasını tavsiye ederim. Disk ve MacID değiştirmek bunlara nispeten daha kolay. Projenize System.Management referansını eklemeniz gerekmektedir.

using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint
    {
        private static string fingerPrint = string.Empty;

        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + biosId() + "\nBASE >> " + baseId()
                    //+"\nDISK >> "+ diskId() + "\nVIDEO >> " + videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }

        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }

        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }

        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }

        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
       
        public static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
       
        //BIOS Identifier
        public static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
       
        //Main physical hard drive ID
        public static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
       
        //Motherboard ID
        public static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
       
        //Primary video controller ID
        public static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
       
        //First enabled network card ID
        public static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", "MACAddress", "IPEnabled");
        }
        #endregion
    }
}