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

C# & ASP.NET: output CSV file with UTF-8 encoding and BOM ( MS Excel friendly )

Trabla: C# & ASP.NET:  output CSV file with UTF-8 encoding and BOM.

Excel correctly opens such CSV files.

Solving:

         /// <summary>
        /// Return CSV utf-8 file
        /// </summary>
        /// <returns></returns>
        public FileResult DownloadCSV( )
        {
           
            string lvCSV = " .... your CSV FILE STRING WITH utf-8 signs like こんにちは世界 ... ";

            string lvFileName = "myfile.csv";

            // UTF8 with BOM (byte order mark)
            UTF8Encoding lvUtf8EncodingWithBOM = new UTF8Encoding(true,true);

            // Byte Order Mark -  \x00EF\x00BB\x00BF
            string lvBOM =
            Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());

            return File( lvUtf8EncodingWithBOM.GetBytes( lvBOM + lvCSV), "text/csv;charset=utf-8", lvFileName);
        }
    }


Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Trabla: Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Solving:

In this tutorial we will implement simple wrapper for www calls and processing it.
Calling of API will be so easy, e.g.

  api.xgSignIn (this, lvLogin, lvPassword);

where this - object which implements handler method 

Naming convention:
I will use prefix X<ClassName>  e.g. XServiceModel.
I will use prefix XI<InterfaceName> e.g. XIServiceCallbackHandler
I will use prefix xg<MethodName> e.g.  void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

1. Create C# script   XServiceEventModel.cs  with following code:

using UnityEngine;
using System.Collections;

public class XServiceEventModel {

    public int id { get; set; }
    public string data{ get; set; }
    public string error{ get; set; }

}



2. Create C# script XIServiceCallbackHandler.cs - interface with only one method.
Any view should implement it in order to process WWW callbacks. copy following code:

using UnityEngine;
using System.Collections;

public interface XIServiceCallbackHandler {

    void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

}


3. Create C# script XApiServic.cs - this class is a wrapper of your web-server api.
Use following code:


using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;

public class XApiService : MonoBehaviour {


  

    private const string API_URL     = "http://mysite.com/api/mygame1";
    private const string APP_TOKEN    = "2ba908bb34566e1ba91a5e570d0287";

    #region Event Types


    public const int EVENT_SIGN_IN_SUCCESS     = 10;
    public const int EVENT_SIGN_IN_FAILED     = 11;

    public const int EVENT_RESULTS_SAVE_SUCCESS = 20;
    public const int EVENT_RESULTS_SAVE_FAILED = 21;

  

    #endregion

   
    public void xgSignIn( XIServiceCallbackHandler callbackHandler, string login, string password ){

        string url = API_URL + string.Format ( "/signin?app={0}&login={1}&password={2}", APP_TOKEN, login, password );

        Dictionary<string, string> headers = new Dictionary<string, string> ();
        headers.Add("Accept","application/json");

        StartCoroutine(WaitForRequest(
                                      new WWW( url, null, headers)
                                      ,     callbackHandler
                                      ,     EVENT_SIGN_IN_SUCCESS
                                      ,        EVENT_SIGN_IN_FAILED
                                      ));
    }


    IEnumerator WaitForRequest(WWW www, XIServiceCallbackHandler callbackHandler, int successEventType, int failedEventType )
    {
        yield return www;

        XServiceEventModel lvServiceEvent = new XServiceEventModel ();
       
        lvServiceEvent.id = www.error == null ? successEventType : failedEventType;
        lvServiceEvent.data = www.text;
        lvServiceEvent.error = www.error;

        // Call Callback Handler
        callbackHandler.xgHandleServiceCallback ( lvServiceEvent );

    }

}



3. Example of  view and using previous classes

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class XSignInViewController : MonoBehaviour, XIServiceCallbackHandler {

    public XGameController gameController;
    public XApiService api;

    public Text txtLogin;
    public Text txtPassword;
    public InputField inpLogin;
    public InputField inpPassword;
    public Button btnSignIn;
    public Button btnBack;
    public Text txtMessageBox;


    // Use this for initialization
    void Start () {

        this.inpLogin.textComponent.text = "";
        this.inpLogin.textComponent.text = "";
        this.txtMessageBox.text = "";
       
    }
   
    // Update is called once per frame
    void Update () {
   
    }


    #region Events

   
    // This method is attached in UnityEditor to Button OnClick
    public void xgDoSignIn(){

        string lvLogin = this.inpLogin.textComponent.text;
        string lvPassword = this.inpPassword.textComponent.text;

        // Very easy call of API
        api.xgSignIn (this, lvLogin, lvPassword);
    }

    #endregion


    #region XIServiceCallbackHandler implementation


    public void xgHandleServiceCallback (XServiceEventModel serviceEvent)
    {
        switch (serviceEvent.id)
        {
       
            case XApiService.EVENT_SIGN_IN_SUCCESS:

            // Save User
            string lvLogin = this.inpLogin.textComponent.text;
            string lvPassword = this.inpPassword.textComponent.text;
            var lvToken = Pathfinding.Serialization.JsonFx.JsonReader.Deserialize<XTokenResponseModel> (serviceEvent.data);

            // DO SOME STAFF

            break;

            case XApiService.EVENT_SIGN_IN_FAILED:
            throw new UnityException ("NOT IMPLEMENTED EVENT_SIGN_IN_FAILED");
            break;

            default:
            throw new UnityException ("EVENT NOT FOUND");
        }
    }

    #endregion

  

}




Unity3D: loading and using sprite atlas from Resources

Trabla: Unity3D: loading and using sprite atlas from Resources


Unity3D load sprite atlas from Resources - tutorial 1



Solving:


1. Create sprite atlas ( .png file images, background transparent )


Unity3D load sprite atlas from Resources - tutorial 2


Unity3D load sprite atlas from Resources - tutorial 3
"sprite-atlas.png" File


2. Create new unity2D project

Unity3D load sprite atlas from Resources - tutorial 4


3. Create folder "Resources" in folder "Assets"
and drag-n-drop sprite atlas file into folder "Resources"

Unity3D load sprite atlas from Resources - tutorial 5



4. Select sprite atlas file - set "Sprite Mode" -> "Multiple" + click "Apply"

Unity3D load sprite atlas from Resources - tutorial 6



5. Click "Sprite Editor" - slice sprite in automatic mode - will create separate sprites.

Unity3D load sprite atlas from Resources - tutorial 7

Unity3D load sprite atlas from Resources - tutorial 8
Slice Result



6. Create following UI structure:
Panel
- Text
- Button
- Image

Unity3D load sprite atlas from Resources - tutorial 9

Unity3D load sprite atlas from Resources - tutorial 10



7. Create new C# script , name it "SpriteAtlasController"  and add as component to "Panel"

8. Copy following code into "SpriteAtlasController.cs"

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Add this directive for UI Components e.g. Text, Button etc.
using System.Collections.Generic; 


public class SpriteAtlasController : MonoBehaviour {

public Button btnChangeImage;
public Text txtImageName;
public Image imgImage;

Sprite[] arrSprites;
int spriteIndexInArray = -1;

// Use this for initialization
void Start () {

Debug.Log("Try to load : sprite-atlas ");
arrSprites = Resources.LoadAll<Sprite>("sprite-atlas");
Debug.Log(arrSprites.Length);


foreach (Sprite lvSprite in arrSprites)
{
Debug.Log(lvSprite.name);

}

ChangeImage();

}

// Update is called once per frame
void Update () {

}

// Call this function when button click
public void ChangeImage(){

spriteIndexInArray = spriteIndexInArray < arrSprites.Length - 1 ? spriteIndexInArray + 1 : 0;


Debug.Log ("spriteIndexInArray : " + spriteIndexInArray );

imgImage.sprite = arrSprites[spriteIndexInArray];
txtImageName.text = arrSprites[spriteIndexInArray].name;
}
}




9. Drag-n-drop UI elements to "SpriteAtlasController.cs" script

Unity3D load sprite atlas from Resources - tutorial 11


10. Add OnClick call of method "ChangeImage()" for Button in UI

Unity3D load sprite atlas from Resources - tutorial 12


Hooray!!! :)

Microsoft Visual Studio: open Source Control Explorer from Team Explorer

Trabla: Microsoft Visual Studio : open Source Control Explorer from Team Explorer


Solving:

1. In Team Explorer window click "home" button

Microsoft Visual Studio: open Source Control Explorer from Team Explorer 1


2. Click "Source Control Explorer"

Microsoft Visual Studio: open Source Control Explorer from Team Explorer 2

C# & ASP.NET MVC : create and download csv

Trabla: C# & ASP.NET MVC : create and download csv example

Solving:

....

namespace MyApp.Controllers
{

        public class ReportController: Controller
        {

              
              public ActionResult DownloadCSV()
              {
                    var lvData = GetReportData();
 
                    // Create string with csv data
                    string lvCSV = GetCSV(  lvData  );  

                    var lvFileName =   string.Format(
                                 "report_{0}.csv", 
                                 DateTime.Now.ToString("yyyy/MM/dd")
                     );

                    return File(
                             System.Text.Encoding.UTF8.GetBytes(lvCSV)
                            "text/csv"
                             lvFileName
                     );      

               }

              // List of  Dictionaries with data
              public static IEnumerator<Dictionary<string,string>> GetReportData()
              {
                      List<Dictionary<string,string>> lvData = new List<Dictionary<string,string>>();
                     
                      Dictionary<string, string> lvRow = new Dictionary<string, string>();
                      lvRow.Add( "Name", "Alex" );
                      lvRow.Add( "Age", "29" ); 

                      lvData.Add( lvRow );

                      lvRow = new Dictionary<string, string>();
                      lvRow.Add( "Name", "John" );
                      lvRow.Add( "Age", "30" ); 
             
                      lvData.Add( lvRow );

                      return  lvDat;

              }

               // Converst List of  Dictionaries into string for csv file
               public static string GetCSV( IEnumerator<Dictionary<string,string>> data )
              {
                        string lvDelimiter = ",";

                        StringBuilder lvCSV =  new StringBuilder();

                       // Headers
                       var lvTotalElements = rows.First().Count();
                       var lvIndex = 0;
                       foreach ( var lvItemKey in rows.First().Keys)
                       {
                            lvCSV.Append(lvItemKey);
                            if (lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
                            lvIndex++;
                        }

                       lvCSV.Append("\n");

                       // Data Rows

                        foreach( var lvRow in rows)
                       {
                             lvTotalElements = lvRow.Count();
                             lvIndex = 0;
                        foreach( var lvItemValue in lvRow.Values)
                       {
                              lvCSV.Append(lvItemValue);
                             if(lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
                             lvIndex++;
                        }


                lvCSV.Append("\n");
            }


            return lvCSV.ToString();

              }

        }

}

C#: get current time string

Trabla: C#: get current time string

Solving:

string lvTimeFormat = "yyyy/MM/dd";
string lvCurrentTime = DateTime.Now.ToString( lvTimeFormat  );

C#: iterate ( loop ) through Dictionary

Trabla: C#: iterate ( loop ) through Dictionary<string,string>

Solving:

// Keys and Values

foreach( var lvItem in lvDictionary ){

      System.Diagnostics.Debug.WriteLine(   lvItem.Key );
      System.Diagnostics.Debug.WriteLine(   lvItem.Value);
}


// Iterate only throw collection of Keys

foreach( var lvItemKey in lvDictionary.Keys ){

      System.Diagnostics.Debug.WriteLine(   lvItemKey );

}

 // Iterate only throw collection of Values

foreach( var lvItemValue in lvDictionary.Values ){

      System.Diagnostics.Debug.WriteLine(  lvItemValue );
    
}


C#: c# analog of java System.out.println | System.out.print

Trabla: C#:  c# analog of java System.out.println | System.out.print

Solving:

In C# you can use:
1) Console.WriteLine | Console.Write
2) System.Diagnostics.Debug.WriteLine | System.Diagnostics.Debug.Write

System.Diagnostics.Debug.WriteLine | System.Diagnostics.Debug.Write
- prints into Output Windows in Visual Studio

Example usage:

string lvMessage = "trololo";
System.Diagnostics.Debug.WriteLine( lvMessage );

Official Docs:
https://msdn.microsoft.com/en-us/library/system.diagnostics.debug.write(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.diagnostics.debug.writeline.aspx

C#: ASP.NET: Console.WriteLine not work ( use Debug.WriteLine )

Trabla: C#: ASP.NET: Console.WriteLine not work

Solving:

In ASP.Net app during debug DO NOT use Console.WriteLine.
Use Debug.WriteLine instead.

System.Diagnostics.Debug.WriteLine( " Hooray!!! " );

C#: ASP.NET: get connection string from Web.config file

Trabla: C#: ASP.NET: get connection string from Web.config file


Solving:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


using Npgsql;

// Add this directive
using System.Configuration;

namespace MyApp.Models{

      public class MyReport{

           /// <summary> 
           /// 
           /// </summary> 
           /// <param name="database"> Database connection string name in Web.config</param> 
           /// <param name="params "></param> 
           /// <returns></returns>
            public static ExecuteReport1( string database, string[] params ){
                  
             string connStr = ConfigurationManager.ConnectionStrings[ database ].ConnectionString;
             
             // Example , Connect to PostgreSQL database via Npgsql
            NpgsqlConnection conn = new NpgsqlConnection(  connStr );
            
            // DO STAFF
             ....

            }

      }

}

Xamarine : Xamarine installation on windows

Trabla: Xamarine : Xamarine installation on windows


Solving:

1. Just go to  download page - https://xamarin.com/download
2. Type some required data
3. Download installer
4. Run it and enjoy installation process :)

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 1

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 2


How to install Xamarine IDE on windows 7 - codingtrabla tutorial 3

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 4

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 5

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 6

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 7

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 8

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 9

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 10

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 11

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 12

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 13

Unity3D: delete child objects in gameobject

Trabla: Unity3D: delete child objects in gameobject

Solving:

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine.UI;

public class DeleteChildObjectsExample: MonoBehaviour
{

public GameObject objectsContainer;


void DeleteChildObjects( GameObject container ){
        if( container  != null ){
               if( container.transform.childCount > 0 ){
                     foreach ( Transform child in container.transform ) {
                          Destroy ( child.gameObject );
                      }
               }
        }
}

void Start(){
   
            this.DeleteChildObjects( objectsContainer   );
    
}

void Update(){
}

}

C# & LINQ: multiple join and group by on multiple fields

Trabla: C# & LINQ: multiple join and group by on multiple fields

Solving:

This  example shows show to join multiple tables
and group data by multiple table columns
using LINQ in C#


To run example use  https://dotnetfiddle.net/



using System;
using System.Collections.Generic;
using System.Linq;
                  
public class Program
{
  
    public class User
    {
        public int id {get;set;}
        public string name {get;set;}
    }
  
    public class Course
    {
        public int id {get;set;}
        public string name {get;set;}
    }
  
    public class CourseExercise
    {
        public int id {get;set;}
        public int courseid {get;set;}
        public string name {get;set;}
    }
  
    public class ExerciseUserResult
    {
        public int id {get;set;}
        public int userid {get;set;}
        public int exerciseid {get;set;}
        public int score {get;set;}
        public int attempt {get;set;}
    }

  
  
    public static void Main()
    {
      
      
        List<User> users = new List<User>
        {
                new User { id = 1, name = "Tommy" },
                new User { id = 2, name = "Jerry" },
                new User { id = 3, name = "Merry" }
        };
      
        List<Course> courses = new List<Course>
        {
                new Course { id = 1, name = "Level A" },
                new Course { id = 2, name = "Level B" }
        };
      
        List<CourseExercise> exercises = new List<CourseExercise>
        {
            new CourseExercise { id = 1, courseid = 1, name = "A1" },
            new CourseExercise { id = 2, courseid = 1, name = "A2" },
            new CourseExercise { id = 3, courseid = 1, name = "A3" },
          
            new CourseExercise { id = 4, courseid = 2, name = "B1" },
            new CourseExercise { id = 5, courseid = 2, name = "B2" },
            new CourseExercise { id = 6, courseid = 2, name = "B3" }
        };
      
        List<ExerciseUserResult> results = new List<ExerciseUserResult>
        {
            // First attempt of user Tommy, course A1
            new ExerciseUserResult{ id=1, userid=1,  exerciseid = 1, score = 10, attempt = 1 },
            new ExerciseUserResult{ id=2, userid=1,  exerciseid = 2, score = 15, attempt = 1 },
            new ExerciseUserResult{ id=3, userid=1,  exerciseid = 3, score = 25, attempt = 1 },
              
            // Second attempt of user Tommy, course A1  
            new ExerciseUserResult{ id=4, userid=1,  exerciseid = 1, score = 6, attempt = 2 },
            new ExerciseUserResult{ id=5, userid=1,  exerciseid = 2, score = 7, attempt = 2 },
            new ExerciseUserResult{ id=6, userid=1,  exerciseid = 3, score = 23, attempt = 2 },
              
            // First attempt of user Tommy, course B1
            new ExerciseUserResult{ id=7, userid=1,  exerciseid = 4, score = 14, attempt = 1 },
            new ExerciseUserResult{ id=8, userid=1,  exerciseid = 5, score = 12, attempt = 1 },
            new ExerciseUserResult{ id=9, userid=1,  exerciseid = 6, score = 21, attempt = 1 },
              
          
          
            // First attempt of user Jerry, course B1
            new ExerciseUserResult{ id=10, userid=2,  exerciseid = 4, score = 34, attempt = 1 },
            new ExerciseUserResult{ id=11, userid=2,  exerciseid = 5, score = 32, attempt = 1 },
            new ExerciseUserResult{ id=12, userid=2,  exerciseid = 6, score = 11, attempt = 1 },
              
          
            // First attempt of user Merry, course B1
            new ExerciseUserResult{ id=13, userid=3,  exerciseid = 4, score = 34, attempt = 1 },
            new ExerciseUserResult{ id=14, userid=3,  exerciseid = 5, score = 32, attempt = 1 },
            new ExerciseUserResult{ id=15, userid=3,  exerciseid = 6, score = 11, attempt = 1 },
              
            // Second attempt of user Merry, course B1
            new ExerciseUserResult{ id=16, userid=3,  exerciseid = 4, score = 34, attempt = 2 },
            new ExerciseUserResult{ id=17, userid=3,  exerciseid = 5, score = 32, attempt = 2 },
            new ExerciseUserResult{ id=18, userid=3,  exerciseid = 6, score = 11, attempt = 2 },  
          
              
        };
      
        // Select - user(name), course(name), attempt from dataset
        var query = from r in results
                    join e in exercises on r.exerciseid equals e.id
                    join c in courses on e.courseid equals c.id
                    join u in users on r.userid equals u.id
                  
                group new { user = u.name, course = c.name, attempt = r.attempt }
                by    new { user = u.name, course = c.name, attempt = r.attempt }
                into groupedData

          
                select groupedData.Key;
       

         // Print data            
        query.ToList().ForEach( x => {
          
            Console.WriteLine(
                string.Format("user = {0}, course = {1}, attempt = {2} ", x.user, x.course, x.attempt )
            );
        
        });
      
      
      
    }
}



Result:
user = Tommy, course = Level A, attempt = 1 
user = Tommy, course = Level A, attempt = 2 
user = Tommy, course = Level B, attempt = 1 
user = Jerry, course = Level B, attempt = 1 
user = Merry, course = Level B, attempt = 1 
user = Merry, course = Level B, attempt = 2

C#: LINQ string array except another string array

Trabla: C#: LINQ string array except another string array

Solving: 

Use Except method


...

string[] cities = { "London", "New York", "Kiev", "Odessa" };
string[] ukraineCities = { "Kiev", "Odessa" };

var exceptUkraineCities = cities.Except( ukraineCities   );

....

php vs c#: c# equivalent of md5 function

Trabla: php vs c#: c# equivalent of php md5 function


Solving:

Need to convert php md5 call to c# equivalent

1. PHP ( use http://phpfiddle.org to run php code online ): 

<?php

$password         = "123";
$salt                   = "lA`c1s439PD9@po0`Mg);Aw";
$hashedPassword = md5( $password . $salt );

echo "Password:         {$password} <br>";
echo "Salt:             {$salt}     <br>";
echo "Hashed Password:     {$hashedPassword} <br>";

?>


Result:
Password: 123 
Salt: lA`c1s439PD9@po0`Mg);Aw 
Hashed Password: ad1b358cedc60d2243caef8dc0604a6f 


2. C# ( use https://dotnetfiddle.net to  run C# code online ):

using System;
                   
public class Program
{
    public static void Main()
    {
       
            string lvPassword = "123";
            string lvSalt = "lA`c1s439PD9@po0`Mg);Aw";
             string lvPassAndSalt = lvPassword + lvSalt;
       
            string lvPhpMD5StringToCompareWith = "ad1b358cedc60d2243caef8dc0604a6f";
       
            string lvHashedPassword = md5(lvPassAndSalt);
       
            Console.WriteLine("Password: " + lvPassword );
            Console.WriteLine("Salt: " + lvSalt);
            Console.WriteLine("Hashed Password: " + lvHashedPassword );
       
            Console.WriteLine("Is equial to php md5? : " + lvHashedPassword.Equals( lvPhpMD5StringToCompareWith )  );
       
    }
   
    public static string md5(string stringToHash ){
       
            byte[] lvAsciiBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(stringToHash);
            byte[] lvHashedBytes = System.Security.Cryptography.MD5CryptoServiceProvider.Create().ComputeHash(lvAsciiBytes);
            string lvHashedString= BitConverter.ToString(lvHashedBytes).Replace("-", "").ToLower();
       
            return lvHashedString;
   
    }
   
}


Result:
Password: 123
Salt: lA`c1s439PD9@po0`Mg);Aw
Hashed Password: ad1b358cedc60d2243caef8dc0604a6f
Is equial to php md5? : True


 

c#: random int between two numbers

Trabla: c#: random int between two numbers

Solving:

Random rnd = new Random();

int v1 = rnd.Next(-100, 101); //Random ints from -100 to 101.

int v2 = rnd.Next(1,10); //Random ints from 1 to 10.

int v3 = rnd.Next(52); // Random ints from 0 to 52.

Official Docs: https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx