Using Enums with a description string

13 Oca 2022 In: .net

        public enum Durum
        {
            [Description("Onay Bekliyor")]
            Onay_Bekliyor = 0,
            [Description("Onaylandı")]
            Onaylandi = 1,
            [Description("Red Edildi")]
            Red_Edildi = 2,
            [Description("Iptal")]
            Iptal = 3            
        }
    
//---------------- 
 
    public static class EnumExtensions
    {
        public static string ToStringDescription(this Enum val)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])val
               .GetType()
               .GetField(val.ToString())
               .GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }
    }
 
//-----------------
 
Durum.Onay_Bekliyor.ToStringDescription() 

Excel to DataTable (Excel2Dt)

24 Ara 2021 In:
public class ExcelOPs
    {
        //boşluksuz excel
        public DataTable exelle(string filePath)
        {
            DataTable dt = new DataTable();
            try
            {

                using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, false))
                {
                    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
                    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                    string relationshipId = sheets.First().Id.Value;
                    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                    Worksheet workSheet = worksheetPart.Worksheet;
                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = sheetData.Descendants<Row>();
                    foreach (Cell cell in rows.ElementAt(0))
                    {
                        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                    }
                    foreach (Row row in rows) //this will also include your header row...
                    {
                        DataRow tempRow = dt.NewRow();
                        int columnIndex = 0;
                        foreach (Cell cell in row.Descendants<Cell>())
                        {
                            // Gets the column index of the cell with data
                            int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));
                            cellColumnIndex--; //zero based index
                            if (columnIndex < cellColumnIndex)
                            {
                                do
                                {
                                    tempRow[columnIndex] = ""; //Insert blank data here;
                                    columnIndex++;
                                }
                                while (columnIndex < cellColumnIndex);
                            }
                            tempRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);

                            columnIndex++;
                        }
                        dt.Rows.Add(tempRow);
                    }
                }
                dt.Rows.RemoveAt(0); //...so i'm taking it out here.

                return dt;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                return dt;

            }
        }
        /// <summary>
        /// Given a cell name, parses the specified cell to get the column name.
        /// </summary>
        /// <param name="cellReference">Address of the cell (ie. B2)</param>
        /// <returns>Column Name (ie. B)</returns>
        public static string GetColumnName(string cellReference)
        {
            // Create a regular expression to match the column name portion of the cell name.
            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(cellReference);
            return match.Value;
        }
        /// <summary>
        /// Given just the column name (no row index), it will return the zero based column index.
        /// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ). 
        /// A length of three can be implemented when needed.
        /// </summary>
        /// <param name="columnName">Column Name (ie. A or AB)</param>
        /// <returns>Zero based index if the conversion was successful; otherwise null</returns>
        public static int? GetColumnIndexFromName(string columnName)
        {

            //return columnIndex;
            string name = columnName;
            int number = 0;
            int pow = 1;
            for (int i = name.Length - 1; i >= 0; i--)
            {
                number += (name[i] - 'A' + 1) * pow;
                pow *= 26;
            }
            return number;
        }
        public static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            if (cell.CellValue == null)
            {
                return "";
            }
            string value = cell.CellValue.InnerXml;
            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }
    }

ShowProgress()

10 Haz 2021 In: .net
OnClientClick="ShowProgress()"  
 
--------------------- 
 
  <script>
        toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "positionClass": "toast-bottom-center",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "4000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
    </script>
    <div class="loading" align="center" style="color: black">
        Lütfen Bekleyiniz...<br />
        <br />
        <img src="css/indicator.gif" alt="" />
    </div>
    <script>
        function ShowProgress() {
            setTimeout(function () {
                var modallo = $('<div />');
                modallo.addClass("modallo");
                $('body').append(modallo);
                var loading = $(".loading");
                loading.show();
                var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
                var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
                loading.css({ top: top, left: left });
            }, 200);
        }
    </script>
    <style>
        .modallo {
            position: fixed;
            top: 0;
            left: 0;
            background-color: black;
            z-index: 120;
            opacity: 0.4;
            filter: alpha(opacity=80);
            -moz-opacity: 0.4;
            min-height: 100%;
            width: 100%;
        }

        .loading {
            font-family: Arial;
            font-size: 10pt;
            border: 5px solid #67CFF5;
            width: 200px;
            height: 100px;
            display: none;
            position: fixed;
            background-color: White;
            z-index: 999;
        }
    </style>

How to use SQLBulkCopy to load data

8 May 2021 In: .net
-Using a stored procedure: 37 seconds
-Using concatenated inline SQL: 45 seconds
-Using Entity Framework: 45 minutes
-Using the SQLBulkCopy class: 4.5 seconds
 
 
1.
 DataTable table = new DataTable();
table.TableName = "LogBulkLoad";
table.Columns.Add("IpAddress", typeof(string));
table.Columns.Add("Identd", typeof(string));
table.Columns.Add("RemoteUser", typeof(string));
table.Columns.Add("LogDateTime", typeof(System. DateTimeOffset));
table.Columns.Add("Method", typeof(string));
table.Columns.Add("Resource", typeof(string));
table.Columns.Add("Protocol", typeof(string));
table.Columns.Add("QueryString", typeof(string));
table.Columns.Add("StatusCode", typeof(int));
table.Columns.Add("Size", typeof(long));
table.Columns.Add("Referer", typeof(string));
table.Columns.Add("UserAgent", typeof(string));
 
 
2.
foreach (var log in logData)
{
DataRow row = table.NewRow();
row["IpAddress"] = log.IpAddress;
row["Identd"] = log.Identd;
row["RemoteUser"] = log.RemoteUser;
row["LogDateTime"] = log.LogDateTime;
row["Method"] = log.Method;
row["Resource"] = log.Resource;
row["Protocol"] = log.Protocol;
row["QueryString"] = log.QueryString;
row["StatusCode"] = log.StatusCode;
row["Size"] = log.Size;
row["Referer"] = log.Referer;
row["UserAgent"] = log.UserAgent;
table.Rows.Add(row);
}
 
 
3.
using (SqlConnection conn = new SqlConnection(Configu rationManager.ConnectionStrings["LogParserContext"]. ConnectionString))
{
conn.Open();
using (SqlBulkCopy s = new SqlBulkCopy(conn))
{
s.DestinationTableName = "LogBulkLoad";
s.ColumnMappings.Add("IpAddress", "IpAddress");
s.ColumnMappings.Add("Identd", "Identd");
s.ColumnMappings.Add("RemoteUser", "RemoteUser");
s.ColumnMappings.Add("LogDateTime", "LogDateTime");
s.ColumnMappings.Add("Method", "Method");
s.ColumnMappings.Add("Resource", "Resource");
s.ColumnMappings.Add("Protocol", "Protocol");
s.ColumnMappings.Add("QueryString", "QueryString");
s.ColumnMappings.Add("StatusCode", "StatusCode");
s.ColumnMappings.Add("Size", "Size");
s.ColumnMappings.Add("Referer", "Referer");
s.ColumnMappings.Add("UserAgent", "UserAgent");
s.WriteToServer((DataTable)table);
}
}
 
 

SQL insert from select

2 May 2021 In:

Copy table data with table structure

SELECT *
INTO DEPARTMENTS_20210502
FROM DEPARTMENTS
WHERE CDate >= '2021.05.02';




        public static string CreateInsert(DataTable table, string tablenamesi,int u)
        {
            string sqlsc = "", sqlvl = "";
            sqlsc = "INSERT INTO "+tablenamesi+" (";
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sqlsc += "[" + table.Columns[i].ColumnName + "],";
                if (table.Columns[i].DataType.ToString() == "System.String")
                    sqlvl += "'" + table.Rows[u][i].ToString() + "',";
                else
                if (table.Columns[i].DataType.ToString() == "System.DateTime")
                {
                    if(table.Rows[u][i]!=System.DBNull.Value)
                    sqlvl += "'" + ((DateTime)table.Rows[u][i]).ToString("yyy.MM.dd HH:mm:ss") + "',";
                    else
                        sqlvl += "NULL,";
                }
                else
                    sqlvl += "'" + (table.Rows[u][i].ToString() == "" ? "0" :
                    table.Rows[u][i].ToString().Replace(",", ".")) + "',";
            }
            if (sqlsc.EndsWith(",")) sqlsc = sqlsc.Substring(0, sqlsc.Length - 1);
            if (sqlvl.EndsWith(",")) sqlvl = sqlvl.Substring(0, sqlvl.Length - 1);
            sqlsc = sqlsc + ") VALUES (" + sqlvl + ")";
            return sqlsc;
        }
 
 
 
 
 
 
  public static string CreateTABLE(string tableName, DataTable table)
        {
            string sqlsc;
            sqlsc = "CREATE TABLE " + tableName + "(";
            for (int i = 0; i < table.Columns.Count; i++)
            {
                sqlsc += "\n [" + table.Columns[i].ColumnName + "] ";
                string columnType = table.Columns[i].DataType.ToString();
                switch (columnType)
                {
                    case "System.Int32":
                        sqlsc += " int ";
                        break;
                    case "System.Int64":
                        sqlsc += " bigint ";
                        break;
                    case "System.Int16":
                        sqlsc += " smallint";
                        break;
                    case "System.Byte":
                        sqlsc += " tinyint";
                        break;
                    case "System.Decimal":
                        sqlsc += " decimal ";
                        break;
                    case "System.DateTime":
                        sqlsc += " datetime ";
                        break;
                    case "System.String":
                    default:
                        sqlsc += string.Format(" nvarchar({0}) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());
                        break;
                }
                if (table.Columns[i].AutoIncrement)
                    sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() + "," + table.Columns[i].AutoIncrementStep.ToString() + ") ";
                if (!table.Columns[i].AllowDBNull)
                    sqlsc += " NOT NULL ";
                sqlsc += ",";
            }
            return sqlsc.Substring(0, sqlsc.Length - 1) + "\n)";
        } 
 

SQL Update with Select command

16 Nis 2021 In:
UPDATE
    Table_A
SET
    Table_A.YDSMaxPuanENG = (select max(yd.puan) from YDSPUAN yd where yd.UYELER_ID=Table_A.UYELER_ID and yd.Iptal=0 and (dil='İNGİLİZCE / ENGLISH' or OSYMHamVeri LIKE '%ENGLISH%'))
FROM
    [DegerlemeList] AS Table_A
 
 
 
-----
 
UPDATE
Table_A
SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2
FROM
Some_Table AS Table_A
INNER JOIN Other_Table AS Table_B
ON Table_A.id = Table_B.id
WHERE 
    Table_A.col3 = '-_-_-' 
 
 

Get Random SipNo

1 Şub 2021 In: .net, ipucu
        public  string GetSipNo()
        {
            Random rn = new Random();
            //yeni
            int lenght = 6;
            StringBuilder rs = new StringBuilder();
            //string charPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string chars = "ABCDEFGHIJKLMNPRSTUVYZ";
    //string nums = "1234567890"; 
            string nums = "123456789";
            while (lenght > 0)
            {
                if (lenght == 6 || lenght == 5 || lenght == 2 || lenght == 1)
                    rs.Append(nums[(int)(rn.NextDouble() * nums.Length)]);

                if (lenght == 3 || lenght == 4)
                    rs.Append(chars[(int)(rn.NextDouble() * chars.Length)]);

                lenght--;
            }

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr_b2b"].ConnectionString))
            {
                using (SqlCommand comm = new SqlCommand(@"SELECT COUNT (SIP_ID) FROM Siparisler WHERE SipNo='" + rs.ToString() + "'"))
                {
                    comm.Connection = conn;
                    conn.Open();
                    if (comm.ExecuteScalar().ToString() != "0") return GetSipNo();
                }
            }
            return rs.ToString();
        }

Ben Kimim ?

Celiker BahceciMerhabalar, ben Çeliker BAHÇECİ. 2004 den beri özel sektörde bilgisayar mühendisligi ve egitmenlik yapıyorum. Yine aynı yılın Ekim ayından beri sitemde .Net ile programlama ve hayat görüşüm ile ilgili makalelerimi yayınlıyorum. Blogum dışında Yazgelistir.com, mobilnedir.com gibi ineta kapsamındaki bir çok siteye Microsoft teknolojileri ile ilgili yazılar yazmaktayım.
Bu site ile sizinde hayatınızı anlamlandırmanızda bir parça katkımın olması dilegiyle...