I’ve been working on a game in Unity for a few weeks and I have been using the WWW object to make POST requests. Problem is that the WWW blocks the rendering thread so long running queries can make the game lag (alot).

To try to fix this I wanted to make a separate thread for all my network calls but since Unity is not thread safe I could not use the WWW request any more.

So I remade the request using the WebClient class. This was working great up until I tried it on windows phone 8. It appears this is not supported on the WP8, the reason for this being that the WP8 has a very limited subset of the .Net framework.

Windows Phone 8 uses a different flavor of .NET called .NET for Windows Phone which is missing some of the types available on other platforms. Youll have to either replace these types with different ones or implement them yourself.

- http://docs.unity3d.com/Manual/wp8-faq.html

If you try to use these methods on the WP8 you get (annoying) messages like these:

Error: method System.Byte[] System.Net.WebClient::UploadData(System.String,System.String,System.Byte[])` doesn’t exist in target framework.

Error: method System.IO.Stream System.Net.HttpWebRequest::GetRequestStream() doesn’t exist in target framework.

Error: method System.Net.WebResponse System.Net.HttpWebRequest::GetResponse() doesn’t exist in target framework.

So after a bit of searching (and alot of trial and error) I arrived at the below code, which works on all platforms.

This is using WebRequests, according to the API for windows phone only certain methods are available so I could only use the async methods, but I’ve written the code so that it appears to be synchronous to the calling method which is what I wanted for my application (as I am calling it from a separate “networking thread” and not in the main thread).

        /// <summary>
        /// Make post request to url with given paramaters
        /// </summary>
        /// <param name="url">URL to post data to http://server.com/method </param>
        /// <param name="data">{ Data: data }</param>
        /// <returns>string server response</returns>
        public string PostData(string url, string data)
        {
            // json request, hard coded right now but use "data" paramater to set this value.
            string jsonRequest = "{\"Data\": \"data\"}"; // the json request

            var request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;

            // this could be different for your server
            request.ContentType = "application/json";

            // i want to do post and not get
            request.Method = "POST";

            // used to check if async call is complete
            bool isRequestCallComplete = false;

            // store the response in this
            string responseString = string.Empty;

            request.BeginGetRequestStream(ar =>
            {
                var requestStream = request.EndGetRequestStream(ar);
                using (var sw = new System.IO.StreamWriter(requestStream))
                {
                    // write the request data to the server
                    sw.Write(jsonRequest);

                    // force write of all content
                    sw.Flush();
                }

                request.BeginGetResponse(a =>
                {
                    var response = request.EndGetResponse(a);
                    var responseStream = response.GetResponseStream();
                    using (var sr = new System.IO.StreamReader(responseStream))
                    {
                        // read in the servers response right here.
                        responseString = sr.ReadToEnd();
                    }
                    // set this to true so the while loop at the end stops looping.
                    isRequestCallComplete = true;
                }, null);

            }, null);

            // wait for request to complete before continuing
            // probably want to add some sort of time out to this
            // so that the request is stopped after X seconds.
            while (isRequestCallComplete == false) { Thread.Sleep(50); }

            return responseString;
        }

0 Comments Game programming, Programming, Unity Tags: , , , Jens Berfenfeldt

This blue pill can help you to enjoy canadian generic viagra with strong erection.

I’ve recently been playing with Unity and got stuck on that I wanted to add event listeners to the buttons that I made in the visual designer programatically and not through the ui interface.

This Code adds an onClick event to any button in the scene, and if any of them are clicked the methodButtonClick is called with the button as a paramater.

In my opinion, this is much nicer than using the messy graphical interface to set it up, and also keeps all the logic in the main game class :)

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

public class GameCode: MonoBehaviour 
{
	void Start () 
	{
		var allUIElements = UnityEngine.UI.Button.allSelectables.ToArray (); 
		foreach (var uiItem in allUIElements) 
		{
			if(uiItem.GetType() == (typeof(Button)))
			{
				Button uiButton = (Button) uiItem;
				uiButton.onClick.RemoveAllListeners();
				uiButton.onClick.AddListener(() => ButtonClick(uiButton));
			}
		}
	}

	public void ButtonClick(Button clickedButton) 
        {
		Debug.Log ("clicked: " + clickedButton.name);
	}
}

 

Intro

The choice between CRM Online and On Premise can initially seem very simple but the truth is there are a few different things that need to be considered, and a few of these might not be apparent right away.

Depending on what your needs are either one can be a suitable candidate.My reason for writing this is that this is a very recurring question I get from both sales people, project managers, and customers. My answer is going to be a bit “techyy” but I hope even non it-people will be able to follow along.

Lets start with one thing which I think most people get wrong.

You cannot start this discussion with: “We want platform X because, <insert random non CRM based argument about why cloud is better or why locally hosted is better, or why your business only uses cloud>”.

What you need to do is look at your business requirements, and I mean actually look at what you need from your CRM system, and how you are going to solve it (this requires the use of someone who knows MS-CRM in detail). If you don’t attack the problem from this direction there is a good chance you might either end up with a system which can’t do what you want, or is simply costing more than it needs to be.

 

The questions you need to ask

So to make this easier I made a list of arguments to consider, if you answeryesto any of these you need an on premise solution, if not, CRM Online will probably suit your needs just fine.

The first thing you should look into is what integrations you need.

If you need to move data to or from CRM online you need to send data through CRM’s organization service. The CRM Online organisation service is not fast (WCF services were never really meant to be fast or used for massive amounts of data). Sending a few requests at a time is never a problem, but when you get up in to thousands in a short period of time this becomes problematic. An example of this might be that a large company wants to move over all their invoices from the economy system to the crm system every night. Some numbers on this are that with single threaded batching you can reach speeds of around 50-100 records / second, with parallelisation and batching you can reach 300 / second under perfect circumstances, but this is something that is harder to code and takes a longer time to build.

  • Do you need to move thousands of records between an external source and your CRM system in very short periods of time?

The second thing to look into are your requirements on business logic.
CRM Online is a shared environment, this means that you are not alone on the hardware that is running the server. At any given point someone else on the same server could be doing some processor intensive task that makes your system a little bit slower.So if your business logic requires the CRM system to do some heavy lifting on the server side, ie: creating lots of records in a plugin, or doing many updates to other records when you save a post. Then this could cause timeouts as the online servers simply can’t always handle the load during peak hours (I have had a few support tickets with Microsoft as a result of this one).

  • Does your business require processor intensive / heavy business logic that involves updating or creating many posts as a result of a change in a record?

The third thing to check is if you need raw data access.
This goes a little bit hand in hand with the first point about integrations, but is even more put on edge in that Microsoft online does not allow you to access the underlying database. That is, you can’t read, write, or even look at the underlying SQL database. This could be important if you for example want to do direct T-SQL queries, or do statistical analysis with data from CRM without using the web interface (you can export to excel and work with that if that’s enough), or perhaps you want to use data from many different databases to create reports in reporting services..

  • Do you need direct access to the database?

The final thing I would check are the security requirements of the business.
Is it ok that the data is being hosted in an environment that the business cannot control. No matter how many assurances you get from another company, unless things are not physically hosted on servers the business owns someone outside the organisation has access to it. This also has a flip-side in that unless you have a strong IT department Microsoft are probably still going to protect your data better than you can do yourself.

  • Is it ok that a 3rd party such as Microsoft has access to your data?

 

Conclusions

Now if you answered yes to any of these questions and you don’t want to (or have the knowledge to) host your CRM solution yourself, there are MANY companies which do this for you at usually quite reasonable costs.

Also keep in mind that this is just a list of extremes, there are always individual considerations with each solution, and there is always the possibility of starting with CRM Online and moving to On premise as your needs expand.

Finally I would also like to point out that CRM Online is perfect for many customers, and if my post has come off as anti-crm-online-ish this is not the intention of the post, I simply want to point out the areas in which cloud based CRM might not always be the best fit. For business where standard CRM, with a few minor tweaks is all that is needed there is no reason to not use CRM Online.

I received this error after switching from the CRM 2013 SDK dlls to the new CRM 2015 SDK .Dll’s.

The type or namespace name ‘Xrm’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?)

Which led me to this StackOverflow question; “Can’t access Microsoft.Xrm namespace” which seems very similar but does not solve my problem.

What eventually led me to a solution was a warning listed further down in the list of errors. It seems that Microsoft with the new SDK has switched to .Net 4.5.2 so the whole problem for me was that I needed to install a later version of .Net (minimum 4.5.2) and then switch target frameworks to this.

This is the warning that led me to this solution:

The primary reference “Microsoft.Xrm.Client, Version=5.0.9689.2166, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL” could not be resolved because it was built against the “.NETFramework,Version=v4.5.2″ framework. This is a higher version than the currently targeted framework “.NETFramework,Version=v4.5.1″.

So the solution turned out to be as simple as getting the developper pack of .Net 4.5.2. and switching target frameworks on my project to this in visual studio.

This little C# class can be used to validate Swedish social security numbers in MVC5.
It will accept numbers with century and numbers with or without a dash or space

It is used like this:

bool isValid1 = SwedishSocialSecurity.IsValid("19811218-9876");
bool isValid2 = SwedishSocialSecurity.IsValid("19811218 9876");
bool isValid3 = SwedishSocialSecurity.IsValid("811218-9876");
bool isValid4 = SwedishSocialSecurity.IsValid("8112189876");

The code:

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

namespace SyntaxWarriors.Tools
{
    public class SwedishSocialSecurity
    {
        public static bool IsValid(string idNumber)
        {
            if (string.IsNullOrEmpty(idNumber))
                throw new FormatException("Not a valid social security number");

            idNumber = idNumber.Trim();

            if (idNumber.IndexOf(' ') != -1)
                idNumber = idNumber.Replace(" ", string.Empty);

            if (idNumber.IndexOf('-') != -1)
                idNumber = idNumber.Replace("-", string.Empty);

            if (idNumber.Length == 12)
                idNumber = idNumber.Remove(0, 2);

            else if (idNumber.Length != 10)
                throw new FormatException("Not a valid social security number");

            return (CalculateControlNumber(idNumber.Substring(0, 9)) == ToInt(idNumber[idNumber.Length - 1]));
        }

        private static int CalculateControlNumber(string idNumber)
        {
            int sum = 0;
            for (int i = 0; i < idNumber.Length; i++)
            {
                int number = ToInt(idNumber[i]) * (1 + ((i + 1) % 2));

                foreach (char c in number.ToString())
                    sum += ToInt(c);
            }

            string szSum = sum.ToString();
            int lastNum = ToInt(szSum[szSum.Length - 1]);

            return (lastNum != 0) ? 10 - lastNum : 0;
        }


        public static int ToInt(char chr)
        {
            return Convert.ToInt32(char.GetNumericValue(chr));
        }
    }
}

Continue reading..

Posting a basic template I have for CRM 2013 Plugins. I usually just copy paste this as a starting point and modify it to my needs.

using System;
using System.ServiceModel;
using System.Web.Services.Protocols;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using System.Linq;
using System.Linq.Expressions;

namespace Plugin
{
    /// <summary>
    /// Author: <insert name of person to blame here>
    /// Created: <date it was created>
    ///
    /// Base C# Plugin template for CRM 2013 Plugin
    /// </summary>
    public class Appointment_SetDayName : IPlugin
    {
        private const string _EntityName = "appointment";
        private const string _Target = "Target";

        private bool IsContextValid(IPluginExecutionContext context)
        {
            if (
                context.InputParameters.Contains(_Target) &&
                context.InputParameters[_Target] is Entity &&
                context.PrimaryEntityName == _EntityName)
            {
                return true;
            }
            return false;
        }

        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            
            if (!IsContextValid(context))
                return;

            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService organization = factory.CreateOrganizationService(context.UserId);

            Entity target = (Entity)context.InputParameters[_Target];
            
            //// simple example code of how to get and set attributes on target
            //DateTime? startTime = (DateTime?) target["scheduledstart"];
            //if (startTime != null)
            //{
            //    string dayOfWeekField = "itrim_day_of_week";
            //    int dayOfWeek = (int) startTime.Value.DayOfWeek;
            //    SetValue(target, dayOfWeekField, new OptionSetValue(dayOfWeek));
            //}
        }

        private static void SetValue(Entity entity, string fieldName, object value)
        {
            if (entity.Attributes.Contains(fieldName) == false)
                entity.Attributes.Add(fieldName, value);

            entity.Attributes[fieldName] = value;
        }
    }
}

Product: Cisco AnyConnect 3.1.04072

Today I had some trouble connecting to my company VPN. After clicking the connect button I and supplied the credentials I got an error message.

—————————
Cisco AnyConnect Secure Mobility Client
—————————
The VPN client agent was unable to create the interprocess communication depot.
—————————
OK
—————————

I simply couldnt connect without any apparent reason. After some googling I found the reason and a solution to the problem.

  1. Click the Start button.
  2. Click on Control Panel.
  3. Click on View Network Status and Tasks
  4. Click on Change adapter settings
  5. Right-click the shared connection and choose Properties
  6. Click the Sharing tab
  7. Clear the Allow other network users to connect through this computer’s Internet connection checkbox
  8. Click OK

Ever wondered when and why the Server/Computer last rebooted? Well there is a couple of ways to find this information. The easiest way (In my opinion), is in the cmd run this command.

NET STATISTICS SERVER | FIND “Statistics since”

But then you will only get the last boot time.

Another way, if you want more information about why the server rebooted/shutdown then you can have a look in the Event Viewer.

First of you have to select the System-folder:

And then you have to start the Filter dialog:

Create a filter on event ID 1074.
Event ID: 1074 will show you who/why the system was shutdown

And now you will find all logs containing information about why the System was shut down.

This is just a base HTML page that I keep on my desktop to use when I want to try out / protype an idea to see how it works.
I’ve got a few of the most common libraries linked in from different CDN’s ready to go.

Sometimes JSFiddle just isen’t enough :)

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>test</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
        <!--<script type='text/javascript' src='http://knockoutjs.com/downloads/knockout-3.0.0.js'></script>
        <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/prototype/1.7.1/prototype.js'></script>
        <script type='text/javascript' src='http://cdn.sencha.io/ext-4.2.0-gpl/ext-all.js'></script>-->

        <style>
            body {
                padding: 0px;
                margin: auto;
            }
            #menu {
            }
            #content {
            }
        </style>

        <script>
            $(document).ready(function () {
                alert("document loaded");
            });
        </script>

    </head>
    <body>
        <div id="menu">menu</div>
        <div id="content">content</div>
    </body>
</html>

Why / Intro

I have a Synology diskstation that has tons of photos on it that I don’t want to loose. The diskstation itself has two disks so it can handle a disk breaking, but if I was to get robbed or have a fire I would still loose all my pictures. So in order to remedy this I wanted to backup all my photos to an off site location every night. There are a few options for this built into the diskstation but frankly they cost more than I want to pay (I’m looking at you Amazon Glacier and HiDrive).

Considering the programs available on the Synology NAS it seems like the easiest solution is to backup the files from the NAS to another location using the FTP server on it. Now I don’t want to modify my NAS or add custom packages to it (like lftp) so I want to make my backup solution pull all new/modified/deleted files from the NAS every night.

Getting down to business

My solution to the problem is to create a remote server (vps) that copies new files from my NAS to a local directory every night. If anything happens to my NAS I can just copy them back from the server whenever I wan’t. This solution will work for backing up any ftp server really.

For this to work you first need to have your NAS set up as an FTP server (set up FTP on Synology NAS)

The first issue was to find a vps server for a reasonable price. My choice came down to buyvm.net whom at the time of posting this are offering a VPS with 250GB of storage for 7 USD / month. Which is more than enough for everything I need to backup (and alot cheaper than all others I could find).

 

Their plan also includes a windows 2003 license so this is what I installed. Once this was done I installed WinSCP which is an advanced command line ftp client with ssl encryption capability (dont want to send anything unencrypted over the internet). So follow this guide and get the command line interface installed on the server: Install WinSCP Guide.

When you have that working it’s just a matter scripting the backup routine in a .bat file and scheduling it using windows scheduler.

Below is an image of the folder structure on the server. The Scripts folder contains all the scripts for backing up the NAS and the data folder will contain the backed up data.

 

This is the code in the backup.bat file. This is the file we will schedule to run in the windows scheduler. It just runs WinSCP with the commands in the WinSCPScript.txt file. So create the backup.bat file and copy paste the code below into it. If you have a different folder structure than me you need to change the file to navigate correctly to your folder structure.

c:
cd ..
cd ..
cd backup
cd scripts

set  stamp=%DATE:/=-%%TIME::=-%
echo Start NAS backup! %stamp% >> log.txt
winscp /console /script=WinSCPScript.txt >> log.txt
echo Done! >> log.txt
echo Done!
echo >> log.txt

This is the WinSCPScript.txt file. It contains the directives for the backup routine. The command I’m using connects to the NAS over FTPS and copies all new and changed files as well as deleting any local files which are no longer on the NAS. You can read more about the command here: WinSCP Synchronize.

option batch abort
option confirm off

open ftp://UserNameHere:PasswordHere@publicAddressToYourNas.domain.com:55 -explicitssl
synchronize local -delete -mirror -filemask="*.*" -criteria=either C:\Backup\Data\ /FolderOnFtpToBackup
close
exit

The log.txt file will be created and filled automatically when you run the backup.bat file.

You can run the backup.bat file directly when you want to backup your NAS, but I want a more hands off approach and created a scheduled task that runs the backup ever night at midnight.

Don’t forget to set the task to run as administrator and also to run even when no one is logged on.