UnityWebRequest metadata


We could grab things like file size, last-modified timestamp etc, even before downloading the the file.

HTTP Header reference

//We could grab things like file size, last-modified timestamp etc, even before downloading the the file. 
#if UNITY_2017_1_OR_NEWER
 UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
#else
 UnityWebRequest request = UnityWebRequest.GetTexture(url);
#endif
 request.method = "HEAD";
 yield return request.Send();
 bool requestHadError;

#if UNITY_2017_1_OR_NEWER
 requestHadError = request.isNetworkError;
#else
 requestHadError = request.isError;
#endif
if (!requestHadError)
{
 double uploadedTimeStamp = MoreAppsUtils.GetUnixTimestamp(request.GetResponseHeader("Last-Modified"));
}
request.Dispose();
request = null;

Upload File to a PHP server using C#

 <?php
//check whether the folder the exists
if(!(file_exists('Data')))
{
  //create the folder
  mkdir('Data');
  //give permission to the folder
  chmod('Data', 0777);
}

//check whether the file exists
if (file_exists('Data/'. $_FILES["file"]["name"]))
{
   echo $_FILES["file"]["name"] . " is success ";
   move_uploaded_file($_FILES["file"]["tmp_name"],'Data/'. $_FILES["file"]["name"]);
}
?>

//Server.cs
public static void UploadToCloud(string filename = book.xml)
{
    WebClient myWebClient = new WebClient();
    
    try
    {
        byte[] responseArray = myWebClient.UploadFile( Constants.XML_SERVER_PATH + "fileupload.php", "POST", filename);
        
        // Decode and display the response.
        Console.WriteLine("\nResponse Received.The contents of the file uploaded is:\n{0}",
            System.Text.Encoding.ASCII.GetString(responseArray));
    }
    catch (Exception e)
    {
        Console.WriteLine("{0} Exception", e);
    }        
}

Xml Encryption/Dycryption

public class SimpleEncryption
{
    #region Constructor
    public SimpleEncryption(string password)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltValueBytes = Encoding.UTF8.GetBytes(SaltValue);

        _DeriveBytes = new Rfc2898DeriveBytes(passwordBytes, saltValueBytes, PasswordIterations);
        _InitVectorBytes = Encoding.UTF8.GetBytes(InitVector);
        _KeyBytes = _DeriveBytes.GetBytes(32);
    }
    #endregion

    #region Private Fields
    private readonly Rfc2898DeriveBytes _DeriveBytes;
    private readonly byte[] _InitVectorBytes;
    private readonly byte[] _KeyBytes;
    #endregion

    private const string InitVector = "T=A4rAzu94ez-dra";
    private const int PasswordIterations = 1000; //2;
    private const string SaltValue = "d=?ustAF=UstenAr3B@pRu8=ner5sW&h59_Xe9P2za-eFr2fa&ePHE@ras!a+uc@";

    public string Decrypt(string encryptedText)
    {
        byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);
        string plainText;

        RijndaelManaged rijndaelManaged = new RijndaelManaged { Mode = CipherMode.CBC };

        try
        {
            using (ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(_KeyBytes, _InitVectorBytes))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        //TODO: Need to look into this more. Assuming encrypted text is longer than plain but there is probably a better way
                        byte[] plainTextBytes = new byte[encryptedTextBytes.Length];

                        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                    }
                }
            }
        }
        catch (CryptographicException exception)
        {
            plainText = string.Empty; // Assume the error is caused by an invalid password
        }

        return plainText;
    }

    public string Encrypt(string plainText)
    {
        string encryptedText;
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        RijndaelManaged rijndaelManaged = new RijndaelManaged {Mode = CipherMode.CBC};

        using (ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(_KeyBytes, _InitVectorBytes))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();

                    byte[] cipherTextBytes = memoryStream.ToArray();
                    encryptedText = Convert.ToBase64String(cipherTextBytes);
                }
            }
        }

        return encryptedText;
    }
}

Simple XML Parsing c#

using System.Xml;
using System.Xml.Linq;


//Load string from xml into a list
private static void BuildScenes()
{

XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load("ios_scenes.xml");
  XmlNodeList sceneNode =  xmlDocument.SelectNodes("//Scenes/Scene");
  foreach(XmlNode node in sceneNode)
  {
   string sceneName = node.InnerText;
   levels.Add(sceneName);
   } 

}

//Sample Xml
<?xml version="1.0" encoding="us-ascii"?>
 <Scenes> 
   <Scene>Any data </Scene>
   <Scene>Any data </Scene>
   <Scene>Any data </Scene>
</Scenes>

MethodInfo Reflection to Create a Delegate

MethodInfo actionMethodInfo = typeof(AdvertisementHelper).GetMethod("AdResultCallback", BindingFlags.Static | BindingFlags.NonPublic);
Action<bool> AdResultCallback = (Action<bool>)Delegate.CreateDelegate(typeof(Action<bool>), actionMethodInfo);

Find installed Apps on Android and Start the intent

import android.content.pm.ResolveInfo;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = UnityPlayer.currentActivity.getPackageManager().queryIntentActivities( mainIntent, 0);

Log.d("Deeplink", String.valueOf(pkgAppsList.size()));
for(ResolveInfo info : pkgAppsList)
{
 ActivityInfo activity = info.activityInfo;
 Log.d("Deeplink", String.valueOf(activity.applicationInfo.packageName));
 if(activity.applicationInfo.packageName.contains("your app bundle id"))
 {
              ComponentName name = new ComponentName(activity.applicationInfo.packageName,activity.name);
  Intent i = new Intent(Intent.ACTION_MAIN);

  i.addCategory(Intent.CATEGORY_LAUNCHER);
  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
  i.setComponent(name);

  UnityPlayer.currentActivity.startActivity(i);
  Log.d("Deeplink", "Launching Intent");
 }
}

Retrive data From a CSV using Python and insert into sql

def begin_import(request_type):
    print '[*] Begin import'
    csv_file = open(csv_file_name, "rb")
    table = csv.DictReader(csv_file)

    try:
        session = Session()
        session_row = FlurryAppMetric()
        for row in table:
            if request_type == "month":
                # Ignore time zone as the current table does not support it
                session_row.date = parse(row["dateTime"]).replace(tzinfo=None)
                session_row.api_key = row["app|apiKey"]
                session_row.country = row["country|iso"]
                session_row.active_users_month = row["activeDevices"]
               
            try:
                session.merge(session_row)
                session.commit()
            except SQLAlchemyError as e:
                print '[*] Failed to merge!' + str(e)
    except SQLAlchemyError as e:
        print '[*] SQLAlchemyError thrown: ' + str(e)
        session.rollback()
        session.close()
    finally:
        session.close()
        csv_file.close()