Search code snippets, questions, articles...

c-sharp code snippets

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);
}