Docs Cheat Sheet
C#
+Array
+using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// ----- >> C# List represents a collection of strongly typed objects
List<string> list_string = new List<string>(){ "one", "two", "three" };
// Check Exists
bool lb_exist = list_string.Contains("two"); // Result : true
bool lb_notexist = list_string.Contains("other"); // Result : false
// Find Index
int li_index_found = list_string.FindIndex(a => a == "two"); // Result : 1
int li_index_notfound = list_string.FindIndex(a => a == "other"); // Result : -1
// Add - Prepend
list_string.Insert(0, "zero"); // Result : [ zero, one, two, three ]
// Add - Append
list_string.Add("four"); // Result : [ zero, one, two, three, four ]
// Remove by Index
list_string.RemoveAt(4); // Will Remove "four", result : [ zero, one, two, three ]
// Remove by Value
list_string.Remove("zero"); // Will Remove "zero", result : [ one, two, three ]
// Loop through data
for(int i=0, max_i=list_string.Count(); i<max_i; i++){
Console.WriteLine(list_string[i]);
}
// ----- >> Dictionary is a generic collection which is generally used to store key/value pairs
Dictionary<string, string> dict = new Dictionary<string, string>(){
{ "key1", "value1" },
{ "key2", "value2" }
};
// Check Key Exists
bool lb_key_exist = dict.ContainsKey("key1"); // Result : true
bool lb_key_notexist = dict.ContainsKey("other"); // Result : false
// Add Key
dict.Add("new-key", "New Value");
// Remove Key
dict.Remove("new-key");
// Loop Key of Dictionary
foreach (KeyValuePair<string, string> pair in dict)
{
Console.WriteLine(pair.Key + " = " + pair.Value);
}
}
}
Conditional Statement
+using System;
public class Program
{
public static void Main()
{
int i = 0;
// If Statement
if (i == 0) {
Console.WriteLine("i equals 0");
} else if (i == 1) {
Console.WriteLine("i equals 1");
} else {
Console.WriteLine("Other");
}
// Switch Statement
switch(i) {
case 0 :
Console.WriteLine("i equals 0");
break;
case 1 :
Console.WriteLine("i equals 1");
break;
default : /* Optional */
Console.WriteLine("Other");
break;
}
}
}
Linq
+Refresh DataContext
int ai_id = 0;
var rs_data = db.GetTable<tbl_data>().SingleOrDefault(d => d.id == ai_id);
// Refresh invalidate cache (source : https://msdn.microsoft.com/en-us/library/system.data.linq.refreshmode%28v=vs.110%29.aspx )
db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, rs_data);
Group By
from x in db.GetTable<tbl_main>()
group x by new{
x.field1,
x.field2
} into y
select new
{
hasil1 = y.Key.field1
hasil2 = y.Key.field2,
hasil3 = y.Sum(d => d.field3),
};
Left Join
from main in db.GetTable<tbl_main>()
join tmp_ref in db.GetTable<tbl_reference>() on main.reff_id equals tmp_swd.reff_id into JoinedReference
from ref in JoinedReference.DefaultIfEmpty()
select new {
id = main.id,
reff_id = main.reff_id,
reff_name = ref.reff_name
};
String
+int ls_strpos_found = ("0123456789").IndexOf("5"); // Output : 5
int ls_strpos_notfound = ("0123456789").IndexOf("A"); // Output : -1
string ls_string = "Some text";
string replacement = Regex.Replace(ls_string, @"\t|\n|\r", "");
string ls_padleft = ("45").PadLeft(5, '0'); // Output : 00045
string ls_padright = ("45").PadRight(5, '0'); // Output : 45000
string ls_substring = ("0123456789").Substring(1, 2); // Output : 12
Text File Operation
+System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true);
file.WriteLine(lines);
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
Web Curl
+using System;
using System.Web;
public class Program
{
public static void Main()
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
// Add Headers
client.Headers.Add("app_id", "MyApp");
// ----- >> Method : GET
string ls_response = client.DownloadString("https://myapi.test?param=" + HttpUtility.UrlEncode("123"));
Console.WriteLine(ls_response);
// ----- >> Method : POST / PUT
string ls_method = "POST"; // [ POST / PUT / DELETE ]
// Append Post Data from Argument Parameter
System.Collections.Specialized.NameValueCollection coll_post = new System.Collections.Specialized.NameValueCollection();
coll_post.Add("key_name", "key_value");
byte[] response = client.UploadValues("https://myapi.test", ls_method, coll_post);
ls_response = System.Text.Encoding.UTF8.GetString(response);
}
}
}
GIT
+CASE 1 : Membuat Branch Baru dari Branch Saat Ini
+Saat ini Bekerja di branchA, lalu ingin buat branch baru dari base branchA bersama yang sudah dikerjakan
git switch -c [NamaBranchBaru]
CASE 2 : Berpindah Sementara ke Branch Lain Tanpa Commit
+Saat ini Bekerja di branchA, lalu diminta untuk pindah ke branchB dan melakukan deploy / hotfix di branchB, tetapi tidak ingin commit dulu pekerjaan di branchA karena nantinya ingin lanjut lagi
git stash push -u -m "Work In Progress [branchA] "
git switch branchB
git fetch
git pull origin branchB
-- lakukan pekerjaan yang diminta disini
-- lakukan commit & push branchB
git switch branchA
git stash pop
CASE 3 : Mengambil Update Terbaru Saat Masih Ada Perubahan Lokal
+Saat ini Bekerja di branchA (semua pekerjaan belum dicommit), lalu ada rekan yang commit & push kode penting di branchA dan menginformasikan developer lain agar pull dulu commit tadi dan lanjutkan pekerjaan di branchA
git stash push -u -m "Work In Progress branchA"
git fetch
git pull origin branchA
git stash pop
CASE 4 : Mengambil Update Terbaru Saat Sudah Ada Commit Lokal
+Saat ini Bekerja di branchA (ada pekerjaan yang sudah dicommit local), lalu ada rekan yang commit & push kode penting di branchA dan menginformasikan developer lain agar pull dulu commit tadi dan lanjutkan pekerjaan dii branchA
git fetch
git pull --rebase origin branchA
# Jika terjadi conflict
# - resolve conflict
git add .
git rebase --continue
# Jika ingin membatalkan rebase
git rebase --abort
CASE 5 : Mengambil Update dari Branch Lain Saat Masih Ada Perubahan Lokal
+Saat ini Bekerja di branchA (semua pekerjaan belum dicommit), lalu ada rekan yang commit & push kode penting di branchB dan menginformasikan developer lain agar pull dulu commit tadi dan lanjutkan pekerjaan di branchA
git stash push -u -m "Work In Progress branchA"
git switch branchB
git pull origin branchB
git switch branchA
git rebase branchB
git stash pop
CASE 6 : Mengisi repository baru yang dibuat di web github
+Saat membuat project aplikasi terkadang repository dibuat belakangan, berikut command yang bisa dipakai, semua dilakukan dalam 1 cmd
1. Masuk ke folder project
- pastikan cursor saat ini sudah didalam folder apps
cd path/ke/appsproject
2. Inisialisasi Git
git init
3. Buat .gitignore (bisa di skip)
4. Cek file yang akan di-commit
git status
5. Tambahkan semua file
git add .
git commit -m "Initial commit"
6. Hubungkan dengan repository GitHub
- Di halaman repository GitHub yang baru kamu buat, copy URL repository-nya. Biasanya bentuknya: https://github.com/USERNAME/NAMA-REPO.git
git remote add origin https://github.com/USERNAME/NAMA-REPO.git
git remote -v
7. Push ke GitHub
git branch -M main
git push -u origin main
(Jika terjadi kendala, biasanya karena ada isi pada repository nya readme.md / license)
git pull origin main --allow-unrelated-histories
git push -u origin main
CASE 7 : Pindahkan semua uncommitted changes dari branchA → branchB baru
+- Saat ini berada di branchA
- Ada 30 changes, semuanya belum di-commit
- Ingin membuat branchB baru
- Semua changes tersebut harus masuk ke branchB
- Setelah itu commit & push branchB
# 1. Pastikan sedang di branchA
git status
git branch --show-current
# 2. Buat branchB baru dan langsung pindah ke sana
git switch -c branchB
# 3. Cek changes
git status
# 4. Commit semua changes
git add .
git commit -m "Your commit message"
# 5. Push branch baru ke remote
git push -u origin branchB
Python
+JSON Handling
+Atur data ke json ataupun sebaliknya
import json
data = {"name": "Nugraha"}
# convert to json
json_data = json.dumps(data)
# convert to dict
dict_data = json.loads(json_data)
Virtual Environment
+# buat venv
python -m venv venv
# aktifkan linux/mac
source venv/bin/activate
# aktifkan windows
venv\Scripts\activate
# install package
pip install django
# freeze
pip freeze > requirements.txt
SQL Server
+Conditional Statement
+DECLARE @condition VARCHAR(1) = '1',
@myresult VARCHAR(100) = '';
SET @myresult = (CASE @condition
WHEN '1' THEN 'Statement 1'
WHEN '2' THEN 'Statement 2'
ELSE 'Other Statement'
END);
DECLARE @condition VARCHAR(1) = '1';
IF ( @condition = '1')
BEGIN
print 'Statement 1';
END
ELSE IF ( @condition = '2')
BEGIN
print 'Statement 2';
END
ELSE
BEGIN
print 'Other Statement';
END
Convert table to cs object
+
DECLARE @TableName SYSNAME = 'namatabel'
BEGIN
DECLARE @Result VARCHAR(MAX)
SET @Result = @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 'char'
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
END
Cursor
+DECLARE @field1 BIGINT,
@field2 VARCHAR(100);
-- Declare Cursor
DECLARE c_trans CURSOR FOR
SELECT field1, field2
FROM myTable
FOR READ ONLY;
OPEN c_trans
WHILE (1 = 1)
BEGIN
FETCH NEXT FROM c_trans INTO @field1, @field2;
IF @@FETCH_STATUS <> 0
BREAK
-- Inside Loop
SELECT @field1 field1, @field2 field2;
END;
-- Deallocate Cursor
CLOSE c_trans;
DEALLOCATE c_trans;
Datetime
+SELECT @myDate myDate; -- 2010-12-31 15:03:01.000+
SET @myDate = DATEADD(DAY, -1, @myDate);
DECLARE @myDate DATETIME = CONVERT(DATETIME, '2011-01-01 15:03:01', 20);
Miscellaneous Query
+Check tipe data kolom dari tabel
EXEC sp_describe_first_result_set N'
SELECT TOP 1 * FROM ITP_MKT.dbo.GATEPASS_TRN gps
'
SELECT DISTINCT
o.name AS Object_Name,
o.type_desc
FROM sys.sql_modules m
JOIN sys.objects o ON m.object_id = o.object_id
WHERE m.definition Like '%keyword%';
-- With Order
SELECT ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber, Field1, Field2, Field3
FROM User
-- Without Order
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 100)) AS of_RowNumber, Field1, Field2, Field3
FROM User
-- With Order and Reset By Group Partition
SELECT ROW_NUMBER() OVER (PARTITION BY field1, field2 ORDER BY Id) AS RowNumber, Field1, Field2, Field3
FROM User
Search Wildcard
+DECLARE @SEARCHSTRING VARCHAR(255), @notcontain Varchar(255)
SELECT @SEARCHSTRING = 'namapencarian', @notcontain = ' '
SELECT DISTINCT sysobjects.name AS [Object Name] ,
case when sysobjects.xtype = 'P' then 'Stored Proc'
when sysobjects.xtype = 'TF' then 'Function'
when sysobjects.xtype = 'TR' then 'Trigger'
when sysobjects.xtype = 'V' then 'View'
when sysobjects.xtype = 'u' then 'table'
end as [Object Type]
FROM sysobjects,syscomments
WHERE sysobjects.id = syscomments.id
AND sysobjects.type in ('P','TF','TR','V' , 'u' )
AND sysobjects.category = 0
AND CHARINDEX(@SEARCHSTRING,syscomments.text)>0
AND ((CHARINDEX(@notcontain,syscomments.text)=0
or CHARINDEX(@notcontain,syscomments.text)<>0))
order by sysobjects.name
Stored Procedure
+ALTER PROCEDURE [dbo].[STORED_PROCEDURE_NAME](
@adt_process_date T_DATE,
@as_userid T_ID,
@ai_errno T_INT OUTPUT,
@as_errmess T_DESC OUTPUT)
AS
SET XACT_ABORT, NOCOUNT ON;
/******************************************************************************
name : [dbo].[STORED_PROCEDURE_NAME]
revisions :
ver date author description
--------- ---------- --------------- ------------------------------------
1.0 02/03/2015 MySelf Creation
******************************************************************************/
DECLARE
@li_trans_count INT,
@li_err_severity INT,
@li_err_state INT;
BEGIN
BEGIN TRY
SET @li_trans_count = @@TRANCOUNT;
IF @li_trans_count = 0
BEGIN TRANSACTION;
-- Put Process Content Here
IF @ai_errno > 0
ROLLBACK TRANSACTION;
ELSE IF @li_trans_count = 0
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND @li_trans_count = 0
ROLLBACK TRANSACTION;
SELECT @ai_errno = ERROR_NUMBER(),
@as_errmess = ERROR_MESSAGE(),
@li_err_severity = ERROR_SEVERITY(),
@li_err_state = ERROR_STATE();
RAISERROR(@as_errmess, @li_err_severity, @li_err_state );
END CATCH
END
String
+DECLARE @str VARCHAR(MAX) = 'String containing new line character';
SELECT REPLACE(REPLACE(@str, CHAR(13), ''), CHAR(10), '');
SELECT LOWER('ABC def'); -- Output : abc def
SELECT UPPER('ABC def'); -- Output : ABC DEF
SELECT CHARINDEX('5','123456789'); -- Output : 5
SELECT CHARINDEX('A','123456789'); -- Output : 0
DECLARE @i INT = 45;
SELECT REPLICATE('0',5 - LEN(@i)) + CONVERT(VARCHAR(10), @i); -- Output : 00045
SELECT CONVERT(VARCHAR(10), @i) + REPLICATE('0',5 - LEN(@i)); -- Output : 45000
SELECT SUBSTRING('0123456789', 1, 2); -- Output : 01