c-sharp code snippets

TDL Create Menu Under - Exceptions report
[#Menu:Exception reports]
 ; Button:Create Voucher from Excel
  ;Button:CreatePurchases
  ;Button:CreateSales
  ;Button:CreateLedgerMaster
  ;GST No in Master
    Add	: Item		: Before 	: @@locQuit	: Blank
	Add	: Indent	: Before 	: @@locQuit	: "Fast Entry - Ril"
	Add	: Item		: Before 	: @@locQuit	: Blank
	Add	: Key Item	: Before 	: @@locQuit	: Excel Import to Tally - Ril : E : Menu		: Import Reliance Data
	
    

[Menu: Import Reliance Data]

	Indent		: "options to Import Reliance only"
	Item		: Blank

	Key Item	: "Stock Creation"				: S :Call: StockCreation
	Key Item	: "Sales Entry"				: E :Call:CreatesalesEntryRil
	;Key Item	: "Sales Entry "			: S : Call: CreateSalesEntry
TDL SQL Read DB
[Collection:SQLiteDBColl]
	ODBC: "DRIVER=SQLite3 ODBC Driver;Database=D:\Db\CustomerInfo.db;LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;" ;; connection string with db file name
	SQL: "Select * from SundryDebtors" ;; Sql Query to access Debtors table
	

[Collection:CustomerDetails]
	Source Collection:SQLiteDBColl
	Compute:ID:$_1
	Compute:Name:$_2
	Compute:Address:$_3
	Compute:State:$_4
	Compute:Contact:$_5
	Compute:Gst:$_6
	
;;let me quickly create a report
	 
 
 [#Menu:GateWayOfTally]
	 Add:Item:Customers Info:Display:Customers Info 
	 
[Report:Customers Info ]
	Form:Customers Info 
	Title:"Customers Info "
	
[Form:Customers Info]
	Part:Customers Info 
	
[Part:Customers Info ]
	Line:CustomersColumn,CustomersBody
	Repeat:CustomersBody:CustomerDetails
	Width:100% page
	Height:100% page
	Scroll:Vertical
	Common Border:Yes
	
[Line:CustomersColumn]
	Border:ThickTopBottom
	Space Top:0.5
	Fields:CusID,CusName,CusAddress,CusState,CusContact,CusGst
	Local:Field:CusID:Set as:"Id"
	Local:Field:CusName:Set as:"Name"
	Local:Field:CusAddress:Set as:"Address"
	Local:Field:CusState:Set as:"State"
	Local:Field:CusContact:Set as:"Contact"
	Local:Field:CusGst:Set as:"Gst"
	Local:Field:default:Border:thinright
	Local:Field:default:Style:EmployeeHdStyle
	Local:Field:default:Align:Left

[Line:CustomersBody]
	Fields:CusID,CusName,CusAddress,CusState,CusContact,CusGst
	Border:thinbottom
	Space Top:0.5
	Local:Field:default:Style:EmployeeStyle
	Local:Field:default:Align:Left
	Local:Field:default:Border:thinright
	
[Field:CusID]
	Set as:$Id
	Width:20
	
[Field:CusName]
	Set as:$Name
	Width:30
	
[Field:CusAddress]
	Set as:$Address
	Width:20
	
[Field:CusState]
	Set as:$State
	Width:20
	
[Field:CusContact]
	Set as:$Contact
	Width:20
	
[Field:CusGst]
	Set as:$Gst
	Width:20
	
[Style:EmployeeStyle]
	Font:"Sans-serif"
	Height:12

[Style:EmployeeHdStyle]
	Font:"Sans-Serif"
	Height:12
TDL Post Sql
[#Menu : Gateway of Tally]

	Add	: Item	: Fun	: Call	: FuncSQL1

[Function : FuncSQL]
	
	Variable	: SQLSTAT	: String
	Return	: String

	00 : Walk  Collection : Ledger
	01 : Set 			  : SQLStat 	: 'Insert into SundryDebtors (Name,Address) Values (' + "'" +$Name + "'" + ',' + "'" + $Parent + "'" + ')'
	02 : Log : ##SQLStat
	06 : Call			  : SQLColl
	05 : END WALK
	
[Function : SQLColl]
	02	: Walk Collection	: SQL Insert Query
	01	: Log : "Test"
	04	: Log	: ##SQLStat
	03	: End Walk

[Collection: SQL Insert Query]
	
	ODBC : "DRIVER=SQLite3 ODBC Driver;Database=D:\Db\CustomerInfo.db;LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;" ;; connection string with db file name
	SQL :  ##SQLStat 
	
[System:Variables]
	
	SQLStat	: ""
	
[Variable : SQLStat]
	
	Type	: String
Push notifications with C#
var logger = new LogHiveApi("your-api-key");
var notification = false;
var response = await logger.AddEventAsync("yourprojectname", "yourgroupname", "your-event-name", "descripton", notification);
C# - enable tls1.2 for old .net versions
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(768 | 3072);
bubble sorting
public static int[] SortArray(int[] array)
{
    int length = array.Length;

    int temp = array[0];

    for (int i = 0; i < length; i++)
    {
        for (int j = i+1; j < length; j++)
        {
            if (array[i] > array[j])
            {
                temp = array[i];

                array[i] = array[j];

                array[j] = temp;
            }
        }
    }

    return array;        
}
Close all excel process using C#
public async Task<bool> closeExcelProcesses()
{
    try
    {
        System.Diagnostics.Process[] process=System.Diagnostics.Process.GetProcessesByName("Excel");
        foreach (System.Diagnostics.Process p in process)
        {
            if (!string.IsNullOrEmpty(p.ProcessName))
            {
                p.Kill();
            }
        }
        TraceService("ALL EXCEL PROCESSES CLOSED");
        return true;
    }
    catch(Exception ex)
    {
        TraceService("ERROR IN CLOSING EXCEL PROCESSES");
        return false;
    }
}
Adjust the height of labels location and autosize to content
Graphics g = CreateGraphics();

SizeF size = g.MeasureString(label1.Text, label1.Font, label1.Width);

label1.Height = int.Parse(Math.Round(size.Height + 2, 0).ToString());

label2.Height = int.Parse(Math.Round(size.Height + 2, 0).ToString());



label2.Location = new Point(label1.Left, label1.Bottom);

label2.Location = new Point(label2.Left, label2.Bottom);

this.Height = label9.Bottom + 35;
Detect when VideoPlayer has finished playing
public VideoPlayer VideoPlayer; // Drag & Drop the GameObject holding the VideoPlayer component 

     void Start() 
     {
          VideoPlayer.loopPointReached += nextFunction;
     }

     void nextFunction()
     {
         //your action
     }
Framerate in Unity
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
 
 public class frameRate : MonoBehaviour {
     public Text fpsText;
     public float deltaTime;
 
     void Update () {
         deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
         float fps = 1.0f / deltaTime;
         fpsText.text = Mathf.Ceil (fps).ToString ();
     }
 }
Close/Quit Application in Unity
Application.Quit();
Toggle Fullscreen
Screen.fullScreen = !Screen.fullScreen;
C# Program to check whether a string contains a substring
using System;
  
class StringChecker {
    // Main Method
    public static void Main()
    {
        String str = "Devsheet";
        String subStr = "sheet";

        Console.WriteLine(str.Contains(subStr));
        // -> true
    }
}
Read content from file using C#
using System;
using System.IO;

public class FileOp {
    public static string GetFileContent() {
        string contentString = System.IO.File.ReadAllText("C:\\filename.json");
        return contentString;
    }
}
Convert json string to object in C# .Net
using System.Web.Script.Serialization;

public class JsonSerialOperations {
    public void DeserailizeJsonString() {
        var jsonString = "{\"firstname\": \"hello\"}";

        var json_serializer = new JavaScriptSerializer();
        var data = (IDictionary<string, object>)json_serializer.DeserializeObject(jsonString);

        Console.WriteLine(data["firstname"]);
    }
}
Send http post request with data in C# using restsharp
using RestSharp;
using System.Net;

public class RequestSender {
    public void UpdateFileStatus() {
        var client = new RestClient("http://your-api/base/url");

        var request = new RestRequest("/create/user", Method.POST);
        request.AddParameter("application/json", "{\"firstname\":\"hello\", \"lastname\":\"world\"}", ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        try {
            client.ExecuteAsync(request, response => 
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //DO Something with response.Content
                }
                else {
                    //Error occured in api
                }
            });
        }
        catch(Exception ex) {
            //Exception occured
        }
    }
}
DataTable to JSON
daReportCard obj = new daReportCard();
                DataTable dt = obj.Load_Summary(year, month);

                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row;
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }

                return Json(serializer.Serialize(rows), JsonRequestBehavior.AllowGet);
            }
Conversion from XLSB to XLSX using microsoft interop
if (!File.Exists(strPath + filename.ToUpper().Replace("XLSB", "xlsx")))
                                {

                                    try
                                    {
                                        Application excelApplication = new Application();
                                        Workbooks workbooks = excelApplication.Workbooks;
                                        // open book in any format
                                        Workbook workbook = workbooks.Open(strPath + filename, XlUpdateLinks.xlUpdateLinksNever, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                                        // save in XlFileFormat.xlExcel12 format which is XLSB
                                        workbook.SaveAs(strPath + filename.Substring(0, filename.Length - 4) + "xlsx", XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                                        // close workbook
                                        workbook.Close(false, Type.Missing, Type.Missing);

                                        // ...
                                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
                                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
                                        // shutdown excel
                                        //excelApplication.Quit();
                                    }
                                    catch (Exception ex)
                                    {
                                        ClientSumDesc = "Load Failed, XLSB File Conversion" + ex;
                                        return true;
                                    }
                                    finally
                                    {

                                        foreach (System.Diagnostics.Process proc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                                        {
                                            proc.Kill();
                                        }
                                    }
                                }
Stochastic texture sampling shader function
//hash for randomness
float2 hash2D2D (float2 s)
{
	//magic numbers
	return frac(sin(fmod(float2(dot(s, float2(127.1,311.7)), dot(s, float2(269.5,183.3))), 3.14159))*43758.5453);
}

//stochastic sampling
float4 tex2DStochastic(sampler2D tex, float2 UV)
{
	//triangle vertices and blend weights
	//BW_vx[0...2].xyz = triangle verts
	//BW_vx[3].xy = blend weights (z is unused)
	float4x3 BW_vx;

	//uv transformed into triangular grid space with UV scaled by approximation of 2*sqrt(3)
	float2 skewUV = mul(float2x2 (1.0 , 0.0 , -0.57735027 , 1.15470054), UV * 3.464);

	//vertex IDs and barycentric coords
	float2 vxID = float2 (floor(skewUV));
	float3 barry = float3 (frac(skewUV), 0);
	barry.z = 1.0-barry.x-barry.y;

	BW_vx = ((barry.z>0) ? 
		float4x3(float3(vxID, 0), float3(vxID + float2(0, 1), 0), float3(vxID + float2(1, 0), 0), barry.zyx) :
		float4x3(float3(vxID + float2 (1, 1), 0), float3(vxID + float2 (1, 0), 0), float3(vxID + float2 (0, 1), 0), float3(-barry.z, 1.0-barry.y, 1.0-barry.x)));

	//calculate derivatives to avoid triangular grid artifacts
	float2 dx = ddx(UV);
	float2 dy = ddy(UV);

	//blend samples with calculated weights
	return mul(tex2D(tex, UV + hash2D2D(BW_vx[0].xy), dx, dy), BW_vx[3].x) + 
			mul(tex2D(tex, UV + hash2D2D(BW_vx[1].xy), dx, dy), BW_vx[3].y) + 
			mul(tex2D(tex, UV + hash2D2D(BW_vx[2].xy), dx, dy), BW_vx[3].z);
}