c# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
c# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

20 Ağustos 2021 Cuma

GetQueryString

  public static string GetQueryString(this object obj)
        {
            var properties = from p in obj.GetType().GetProperties()
                             where p.GetValue(obj, null) != null
                             select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());

            return String.Join("&", properties.ToArray());
        }

6 Mayıs 2021 Perşembe

Sap WSDL Basic Auth

  private static Z_PPGEN_HMLOG_PLAKAClient MyBasicConfiguredService()
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
            basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;//mandatory
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;//mandatory

            EndpointAddress endpoint = new EndpointAddress(Url);

            var client = new Z_PPGEN_HMLOG_PLAKAClient(basicHttpBinding, endpoint);

            client.ClientCredentials.UserName.UserName = UserName;
            client.ClientCredentials.UserName.Password = Password;

            return client;
        }

8 Kasım 2020 Pazar

QueryParamsModel

using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Model.Model { public class QueryParamsModel { public string Filter { get; set; } public string SortOrder { get; set; } public string SortField { get; set; } public int PageSize { get; set; } public int PageNumber { get; set; } public IQueryable Sort(IQueryable query) { if (!string.IsNullOrEmpty(this.SortField)) { var entityType = typeof(T); var property = entityType .GetProperties() .FirstOrDefault(c => c.Name.ToLowerInvariant() == this.SortField.ToLowerInvariant()); if (property != null) { var parameterExp = Expression.Parameter(entityType); var memberExp = Expression.MakeMemberAccess(parameterExp, property); var bodyExp = Expression.Convert(memberExp, typeof(object)); var lambdaExp = Expression.Lambda>(bodyExp, parameterExp); if (this.SortOrder == "desc") { query = query.OrderByDescending(lambdaExp); } else { query = query.OrderBy(lambdaExp); } } } return query; } } }

31 Ağustos 2020 Pazartesi

Enlem boylam uzaklık hesaplama (c#)

 using System;

namespace Falcon.Core.Helpers
{
    public class GeoCalculator
    {
        private static double ToRadians(double degree)
        {
            return (degree * Math.PI) / 180;
        }

        public static double Distance(double latitude1, double latitude2, double longitude1, double longitude2)
        {
            // The math module contains
            // a function named toRadians
            // which converts from degrees
            // to radians.
            longitude1 = ToRadians(longitude1);
            longitude2 = ToRadians(longitude2);
            latitude1 = ToRadians(latitude1);
            latitude2 = ToRadians(latitude2);

            // Haversine formula
            double diffLongitude = longitude2 - longitude1;
            double diffLatitude = latitude2 - latitude1;
            double a = Math.Pow(Math.Sin(diffLatitude / 2), 2) +
                       Math.Cos(latitude1) * Math.Cos(latitude2) *
                       Math.Pow(Math.Sin(diffLongitude / 2), 2);

            double c = 2 * Math.Asin(Math.Sqrt(a));

            // Radius of earth in
            // kilometers. Use 3956
            // for miles
            double r = 6371;

            // calculate the result
            return (c * r);
        }
    }
}

3 Aralık 2018 Pazartesi

Enum Display Name'ini çekme

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum enu)
    {
        var attr = GetDisplayAttribute(enu);
        return attr != null ? attr.Name : enu.ToString();
    }

    public static string GetDescription(this Enum enu)
    {
        var attr = GetDisplayAttribute(enu);
        return attr != null ? attr.Description : enu.ToString();
    }

    private static DisplayAttribute GetDisplayAttribute(object value)
    {
        Type type = value.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException(string.Format("Type {0} is not an enum", type));
        }

        // Get the enum field.
        var field = type.GetField(value.ToString());
        return field == null ? null : field.GetCustomAttribute<DisplayAttribute>();
    }
}

30 Temmuz 2018 Pazartesi

Tüm TimeZone'ları çekip veritabanına ekleme

            var tzCollection = TimeZoneInfo.GetSystemTimeZones();
            var timeZoneTypes = new List<TimeZoneType>();
            foreach (var timeZoneInfo in tzCollection)
            {
                var timeZoneType = new TimeZoneType
                {
                    TimeZoneInfoId = timeZoneInfo.Id,
                    DaylightName = timeZoneInfo.DaylightName,
                    DisplayName = timeZoneInfo.DisplayName,
                    StandardName = timeZoneInfo.StandardName,
                    SupportsDaylightSavingTime = timeZoneInfo.SupportsDaylightSavingTime,
                    Ticks = timeZoneInfo.BaseUtcOffset.Ticks
                };
                timeZoneTypes.Add(timeZoneType);
            }
            foreach (var timeZoneType in timeZoneTypes)
            {
                db.TimeZoneTypes.Add(timeZoneType);

                db.Commit();
            }


19 Ekim 2016 Çarşamba

Asp Webform'da dosyayı sayfaya basmak

              string filePath ="c:\\falan\\filan.jpg"

                byte[] buffer = File.ReadAllBytes(filePath);

                Response.ContentType = "image/jpeg";
                Response.OutputStream.Write(buffer, 0, buffer.Length);
                Response.AddHeader("Content-Disposition", "filename=filan.jpg");

filename yanına ";attachment" eklersek sayfa açılırken dosyayı indirmeye başlayacaktır

ContentType : application/pdf, image/jpeg , image/png, image/bmp
gibi

15 Ağustos 2016 Pazartesi

Çalışma zamanı metot üretip çalıştırma

                Type type = Type.GetType("Namespace.ClassName");
                MethodInfo method = type.GetMethod("MethodName");
                object targetClass = Activator.CreateInstance(type);
                object[] paramters= new object[] { paramter1,..., parameterN };
                method.Invoke(targetClass, paramters);

14 Haziran 2016 Salı

9 Şubat 2016 Salı

Entity framework tablo var mı

            bool exists = context.Database
                      .SqlQuery<int?>(@"
                         SELECT 1 FROM sys.tables AS T
                         INNER JOIN sys.schemas AS S ON T.schema_id = S.schema_id
                         WHERE S.Name = 'SchemaName' AND T.Name = 'Table_Name' ")
                      .SingleOrDefault() != null;

25 Aralık 2015 Cuma

Nesne büyüklüğü öğrenme

    /// <summary>
    /// Calculates the lenght in bytes of an object 
    /// and returns the size 
    /// </summary>
    /// <param name="TestObject"></param>
    /// <returns></returns>
    private int GetObjectSize(object TestObject)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        byte[] Array;
        bf.Serialize(ms, TestObject);
        Array = ms.ToArray();
        return Array.Length;
    }

18 Aralık 2015 Cuma

Entity Framework one-to-zero or one relationship

Configure One-to-One Relationship:

We are going to configure a One-to-One relationship between Student and StudentAddress. As you may know, a one-to-one relationship happens when the primary key of one table becomes PK & FK in another table. Here, StudentId is a Primary key of Student table so StudentId should be PK and FK in StudentAddress table in order to have one-to-one (actually one-to-zero or one) relationship between them.
Note that a one-to-one relationship is technically not possible in MS SQL Server. It will always be one-to-zero or one.
Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many, and many-to-many relationships.

Configure one-to-zero or one relationship using DataAnnotations:

The following example shows one-to-one relationship is configured using DataAnnotations attributes.
public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress StudentAddress { get; set; }

}
     
public class StudentAddress 
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}
        
As you can see in the above Student and StudentAddress class, we haven't done anything special in Student class because it follows the code first conventions, so StudentId will become PK. Now, we have used the Key and ForeignKey attributes for StudentId property in StudentAddress class, in order to mark it as PK as well as FK. Notice that we have specified Student entity in the ForeignKey attribute. Thus, Code-First will create a one-to-one relationship between Student and StudentAddress using DataAnnotations attributes.

Configure One-to-Zero-or-One relationship using Fluent API:

The following example sets one-to-zero or one relationship between Student and StudentAddress using Fluent API.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);
        
    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasOptional(s => s.StudentAddress) // Mark StudentAddress is optional for Student
                .WithRequired(ad => ad.Student); // Create inverse relationship

}
        
As you can see in the above example, we set primary key to StudentId for StudentAddress because it doesn't follow the Code-First conventions for PK. In the second line, HasOptional method makes StudentAddress property nullable and then WithRequired method creates inverse relationship by making StudentId column as FK in StudentAddress table. Thus, StudentId will be PK and FK in StudentAddress which makes one-to-zero or one relationship.
Alternatively, you can also configure StudentAddress entity, as shown below.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);
        
    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
                .HasRequired(ad => ad.Student) 
                .WithOptional(s => s.StudentAddress); 

}
        
So, DataAnnotations and Fluent API example for one-to-zero or one relationship will create the following database:
one-to-one relationship in code first
You can check the relationship between Student and StudentAddress in the database, as shown below:
one-to-one relationship in code first
If you create an entity data model of a created database then it will appear like the diagram shown below:
one-to-one relationship in code first
Learn how to create a one-to-many relationship in the next section.

15 Aralık 2015 Salı

string tarihi DateTime a çevirme

 string dateText = "21/12/2015";
var date = DateTime.ParseExact(dateText , "dd/MM/yyyy", null);

4 Aralık 2015 Cuma

EntityFramework savechanges olmadan önce bir önceki değeri alma

db.Users.Attach(user);
var current = db.Entry(user).CurrentValues.Clone();
db.Entry(user).Reload();
//Do you user(from db) stuff
db.Entry(user).CurrentValues.SetValues(current);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();

14 Ekim 2015 Çarşamba

Json nesne döndürme

return Json(JsonConvert.SerializeObject(result), JsonRequestBehavior.AllowGet);

26 Ağustos 2015 Çarşamba

Abstract Factory Method Tasarım Deseni

Factory Method tasarım deseni, nesne oluşturma ihtiyacı doğrultusunda ortaya çıkmış bir tasarım desenidir. Bu tasarım deseni, oluşturulacak somut nesnenin türünü belirlemeye gerek duymadan nesne oluşturma işlemini temel almaktadır.
Resim-1
Resim-1
Factory deseninin temel amacı nesne oluşturma karmaşıklığını kullanıcıdan gizlemektir. Ayrıca kullanıcı, oluşturulacak nesnenin somut türünü belirlemek zorunda değildir. Bunun yerine somut nesnenin implemente edildiği soyut tür olan interface veya abstract class tipini bilmesi yeterlidir. Yani sorumluluk somut nesnelerden soyut nesnelere aktarılmaktadır. Genel olarak Factory sınıflar “static” erişim belirleyicili bir metod barındırırlar. Bu metod, kullanıcıya interface veya abstract class tipinde bir nesne döndürür. Bu sayede kullanıcılar, alt sınıfların oluşturulması sorumluluğundan dolayı oluşabilecek hatalardan da uzak tutulmuş olur.
Örnek Uygulama
Bu örnek uygulamamızda Grafik türüne göre Grafiğin temsilini yapan Sembollerin oluşturulmasını Factory Method yöntemiyle üretmeyi amaçlamaktayız.
Yukarıdaki şekildeki tasarım deseninin uygulanışını şu şeklide yapabiliriz.
Resim - 2
Resim – 2
Gerçek bir uygulamadan alarak göstereceğim bu örnekte bir REST servisinden gelen Graphic nesnesinin türüne göre sembol nesnesinin belirlenmesi işlemini Factory Method inceleyeceğiz. Tabi bu örnekteki konumuz Factory uygulaması olduğundan Servis işlemlerini temsili olarak göreceğiz. Bizi ilgilendiren sadece nesne üretimi olduğundan nesne üretim aşamasını inceleyeceğiz.
public class Graphic
{
   public Symbol Symbol { get; set; }
}
Bize servis tarafından sunulan Graphic nesnesi Null olarak gelmektedir. Biz yazılım tarafında Graphic nesnesinin türüne göre Sembolünü üretmekle sorumluyuz.
public abstract class Symbol
{
     public abstract void draw();
}
Symbol sınıfının soyut bir tip olduğunu görüyoruz. Graphic sınıfında da bu soyut tip kullanılmıştır.
public class SimpleLineSymbol: Symbol
{
    public override void draw()
    {
       // Draw line
    }
}
 
public class SimpleFillSymbol: Symbol
{
     public override void draw()
     {
       // Draw polygon
     }
}
 
public class SimpleMarkerSymbol: Symbol
{
    public override void draw()
    {
       // Draw point
    }
}
Somut sembol sınıfları ise SimpleLineSymbol, SimpleFillSymbol, SimpleMarkerSymbol şeklinde oluşturulmuştur.
public class GraphicSymbolFactory
{
    public static Symbol GetSymbol(Graphic graphic)
    {
        if(graphic is Point)
           return new SimpleMarkerSymbol();
        if(graphic is Polygon)
           return new SimpleFillSymbol();
        if(graphic is Polyline)
           return new SimpleLineSymbol();
 
        throw new InvalidExpressionException("Unknown graphic type");
    }
 
}
GraphicSymbolFactory sınıfına eklediğimiz GetSymbol metodu, Graphic türüne göre somut olan Symbol tiplerini oluşturmaktadır. Dikkat edecek olursak kullanıcıya soyut olan bir Symbol tipi vermekteyiz. Yani içerde olup bitenden kullanıcılar haberdar değildir.
public class GraphicService
{
    private readonly IGraphicRestService service;
 
    public GraphicService(IGraphicRestService service)
    {
       this.service = service;
    }
 
    public Graphic GetGraphicsFromRESTService(string serviceUrl)
    {
       Graphic graphic = service.GetGraphic(serviceUrl);
 
       graphic.Symbol = GraphicSymbolFactory.GetSymbol(graphic);
 
       return graphic;
    }
 
}
GraphicService sınıfı içerisinde tanımlı GetGraphicsFromRESTService metodu, bir servis yardımıyla Graphic nesnesini elde etmektedir. Gelen Graphic nesnesinin sembolü ise kullanıcı tarafından Factory sınıfı yardımıyla belirlenir. Burada kullanıcı diye adlandırdığımız GraphicService sınıfıdır aslında. Çünkü API içerisinde hazırladığımız GraphicSymbolFactory tipini kullanan sınıftır. Kullanıcı sınıf aslında Symbol tipinden türetilen SimpleLineSymbol veya SimpleFillSymbol gibi tiplerden haberdar değildir. Bu somut tipleri oluşturmak zorunda da değildir. Bu karmaşık sorumluluğu Factory deseni ile bir sınıfa aktarmış olduk.

22 Temmuz 2015 Çarşamba

backslah çift tırnak

string a = "hello, world";                // hello, world
string b = @"hello, world";               // hello, world
string c = "hello \t world";              // hello world
string d = @"hello \t world";             // hello \t world
string e = "Joe said \"Hello\" to me";    // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me";   // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = @"\\server\share\file.txt";    // \\server\share\file.txt

16 Haziran 2015 Salı

String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

21 Mayıs 2015 Perşembe

.net 6 mapget kullanımı

 app.UseEndpoints(endpoints => {     endpoints.MapGet("/", async context =>     {         var response = JsonConvert.Seriali...