Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Monday, February 12, 2018

Get the index of an item in a list in C#

int index = myList.FindIndex(a => a.Prop == oProp);
If you don't want to use LINQ, then:
int index;
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i].Prop == oProp)
    {
       index = i;
       break;
    }
}

Sunday, February 11, 2018

Validate Date in C#

DateTime dt;
if (DateTime.TryParseExact(str, "M/d/yyyy", null, DateTimeStyles.None, out dt) == true)
{
//your date is valid and is in dt
}

Tuesday, January 2, 2018

Generate class from database table

 declare @TableName sysname = 'tbBatch'
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

Tuesday, November 7, 2017

Create Log in c#

We can easliy create log by using File.AppendAllText() method because by using this method, it is guaranteed that the file handle will be closed, even if exceptions are raised.
1
2
3
4
5
6
7
public static class Logger
{
    public static void Log(string message)
    {
        File.AppendAllText("C:\\LogFile.txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ":\t" + message + Environment.NewLine);
    }
}

Wednesday, December 7, 2016

Append TimeStamp to a File Name C#

DateTime.Now.ToString("yyyyMMddHHmmssfff")
string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}",DateTime.Now);
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).
With Extension Method
Usage:
string result = "myfile.txt".AppendTimeStamp();
//test20160604234625642.txt
public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

Friday, July 22, 2016

The server response was: 5.5.1 authentication required in Gmail

Introduction 
          Today i came  across an forum post saying  cant able to send a mail to his domain that he purchased but able to send mail to gmail to gmail.The actual is gmail wants the clients to be secure even throw we set EnableSsl = true;
simply it wont work.
       
           To fix the issue add the RemoteCertificateValidationCallback then it will work fine.
  1. public class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             string senderID = "xxx@gmail.com";  
  6.             string senderPassword = "xxxx";  
  7.             RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;  
  8.             string body = "Test";  
  9.             try  
  10.             {  
  11.                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);  
  12.                 ServicePointManager.Expect100Continue = true;  
  13.                 MailMessage mail = new MailMessage();  
  14.                 mail.To.Add("danish.habib@plan-international.org");  
  15.                 mail.From = new MailAddress(senderID);  
  16.                 mail.Subject = "My Test Email!";  
  17.                 mail.Body = body;  
  18.                 mail.IsBodyHtml = true;  
  19.                 SmtpClient smtp = new SmtpClient();  
  20.                 smtp.Host = "smtp.gmail.com";  
  21.                 smtp.Credentials = new System.Net.NetworkCredential(senderID, senderPassword);  
  22.                 smtp.Port = 587;  
  23.                 smtp.EnableSsl = true;  
  24.                 smtp.Send(mail);  
  25.                 Console.WriteLine("Email Sent Successfully");  
  26.             }  
  27.             catch (Exception ex)  
  28.             {  
  29.                 Console.WriteLine(ex.Message);  
  30.             }  
  31.             finally  
  32.             {  
  33.                 ServicePointManager.ServerCertificateValidationCallback = orgCallback;  
  34.             }  
  35.         }  
  36.   
  37.         private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)  
  38.         {  
  39.             return true;  
  40.         }  
  41.     }