20 Ağustos 2021 Cuma
GetQueryString
{
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;
}
21 Kasım 2020 Cumartesi
8 Kasım 2020 Pazar
QueryParamsModel
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.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 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
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
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ı
.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:
15 Aralık 2015 Salı
string tarihi DateTime a çevirme
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
26 Ağustos 2015 Çarşamba
Abstract Factory Method Tasarım Deseni
Ö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.
public class Graphic { public Symbol Symbol { get ; set ; } } |
public abstract class Symbol { public abstract void draw(); } |
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 } } |
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" ); } } |
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; } } |
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#]
Custom DateTime Formatting
There are following custom format specifiersy
(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 zoneYou can use also date separator
/
(slash) and
time sepatator :
(colon). These characters will be
rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator
and DateTimeFormatInfo.TimeSeparator.[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 DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains valueh:mm tt
for en-US
culture and value HH:mm
for de-DE culture.Following table shows patterns defined in DateTimeFormatInfo 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 |
SortableDateTimePattern | yyyy'-'MM'-'dd'T'HH':'mm':'ss (*) |
u |
UniversalSortableDateTimePattern | yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*) |
(*) = culture independent |
[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...
-
Komut ekranına aşagıdaki komutları yazarak windows service işlemlerini gerçekleştirebiliriz. Not : Komut ekranı (Başlat -> Çalıştır -...
-
COMMAND PROMPT TEMEL VE İLERİ DÜZEY ANLATIM Command Prompt komutlarını anlatmaya başlamadan önce, MS-DOS komut türlerine değinelim. Komut...
-
(3)BİN (6)MİLYON (9)MİLYAR (12)TRİLYON (15)KATRİLYON (18)KENTİLYON (21)SEKSİLYON (24)SEPTİLYON (27)OKTİLYON (30)NONİLYON (33)DESİL...