Stream is not writable when i try use a StreamReader constructed by the same fileStream? - filestream

As code after, i don't want create fileStream twice, so i write streamWriter inside fileStream. But it was so strange that code throw an exception when try to instance a StreamWriter. I guess fs's read pointer reach at the end, but it's just a guess. I wanna know why meet this error. Please help me!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Stream
{
class Program
{
static void Main(string[] args)
{
string fileName = "E:\\test.txt";
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamReader r = new StreamReader(fs)) {
}
using (StreamWriter w = new StreamWriter(fs)) {
//exception when new StreamWriter(fs)
//stream is not writable. why? why? why?
}
Console.ReadKey();
}
}
}
}

when finished using(StreamReader r = new StreamReader(fs)), code will invoke fs's close() automatically. So when next using fs, there is a check in StreamWriter's constructor: if(steam ==null ){throw new ArgumentException("stream is not writable")}. There it is!

Related

Unity deserializing an object in another project

I am creating a tool that helps the artist in my studio design their UI easily, and then give them the ability to export the UI to the developers to use in their projects.
Long story short, I followed this tutorial: What is the best way to save game state?
and it worked correctly when I wrote everything in the same script.
However when I opened another unity project to import the data, it stopped working correctly. It would read the file, but then the spawnObject variable which is supposed to be instantiated stays null.
The class I use here is called UIdata, and it has only one gameobject variable which is inputObject, and the class is exactly the same as the one I am exporting from the other project
I am not quite sure why it is not working, can deserialization work if its importing something from another project?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System;
public class DataSaver
{
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
public static T loadData<T>(string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
else
{
Debug.Log("found file");
}
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
string jsonData = Encoding.ASCII.GetString(jsonByte);
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
}
[System.Serializable]
public class UIData
{
public GameObject inputObject;
}
public class LoadingScript : MonoBehaviour
{
private GameObject objectToSpawn;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
importObject();
}
}
public void importObject()
{
UIData loadedData = new UIData();
loadedData = DataSaver.loadData<UIData>("UI");
objectToSpawn = loadedData.inputObject;
if (loadedData == null)
{
return;
}
print(objectToSpawn);
}
}
#Programmer is correct, you cannot serialize engine types. There are several ways to go about resolving your issue. The first is to rebuild your gameobject by serializing its MonoBehaviour components in the following manner (pseudocode):
public GameObject TestSaveAndLoadComponent(MyMonoBehaviour myComponent, GameObject objectToLoadComponentOnto){
// convert component to Json
string jsonString = JsonUtility.ToJson(myComponent);
// Pretend to save the json string to File
string directory = "TestDirectory";
string file = "objectFile";
SaveLoadData.SaveString(directory,file,objectJson);
// load string from file
string loadString = SaveLoadData.LoadString(directory,file);
// add a MonoBehaviour component to the object so that it can be
// overwritten by the JsonUtility
MyMonoBehaviour componentToOverwrite = objectToLoadComponentOnto.AddComponent<MyMonoBehaviour>();
JsonUtility.FromJsonOverwrite(loadString, componentToOverwrite);
return newObject;
}
JsonUtility may not provide a deep copy of your your monoBehaviour class, I don't use it much. It's pretty bare bones, and if it doesn't meet your needs, there's always Json.Net for unity.
All that being said, you shouldn't need to serialize gameObjects or monobehaviours if you structure your code in the proper way, using an Model-view-controller pattern. In such a case you would only need to serialize very simple classes that define the Model for the UI, and then the your view classes would rebuild the ui in a separate scene or project from the given model.

Chat Application using SignalR and Ionic

I am developing a chat application.I use SignalR and Ionic for this.And I get an error on the Ionic side.
Startup.cs
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR.Startup))]
namespace SignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
ChatHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalR
{
public class ChatHub : Hub
{
public void Send(string username,string message)
{
Clients.All.sendMessage(username,message);
}
}
}
controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function ($scope) {
$scope.name = 'Onur'; // holds the user's name
$scope.message = ''; // holds the new message
$scope.messages = []; // collection of messages coming from server
$scope.chatHub = null; // holds the reference to hub
$scope.chatHub = $.connection.chatHub; // initializes hub
$.connection.hub.start(); // starts hub
// register a client method on hub to be invoked by the server
$scope.chatHub.client.broadcastMessage = function (name, message) {
var newMessage = name + ' says: ' + message;
// push the newly coming message to the collection of messages
$scope.messages.push(newMessage);
$scope.$apply();
};
$scope.newMessage = function () {
// sends a new message to the server
$scope.chatHub.server.sendMessage($scope.name, $scope.message);
$scope.message = '';
};
})
Faield to load resource
hubs(0,0)
TypeError: Cannot read property 'chatHub' of undefined
I'm getting errors.Where am I doing wrong.Help me
You need to start the hub after registering client methods. It should work.

How to upload video with Facebook graph API

I've been struggling for weeks to get figure out how to upload video using the graph api. I've gone through all the documentation and i just don't understand what i must do to get a correct response from the graph api before i write the code. I've included an image.
Can someone just tell me like a child what I must put in exactly?
Figured out how to use graph api with c# for unity.
you can post a comment and post a video.
the url given is just an open video that was available, choose your own if you want, or if it becomes unavailable in the future.
enjoy!
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
WWW www = new WWW("http://techslides.com/demos/sample-videos/small.mp4");
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Video.MOV","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}
I will post another forum thread where you answered yourself and that helped me in addition to your answer here.
http://answers.unity3d.com/questions/1167534/how-to-send-file-local-path-using-wwwform-on-ios-a.html
In short, for anyone looking to "Upload Videos using the FB SDK from iOS", follow Luke's answer and add the following:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
///ADD THIS
//this is the path to your file.
String VideoLocStr = Application.persistentDataPath + "Your_Video.mov"
String pathForIOS = VideoLocStr.Replace (" ","%20");
WWW www = new WWW(pathForIOS);
///
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Your_Video.mov","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}
Thanks, Luke.
Good luck to everyone.

Reactive Extensions: Why does this exit immediately?

I am reading IntroToRx and I'm having a bit of trouble with the sample code. Here is the sum total of my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LearningReactiveExtensions
{
public class Program
{
static void Main(string[] args)
{
var observable = Observable.Interval(TimeSpan.FromSeconds(5));
observable.Subscribe(
Console.WriteLine,
() => Console.WriteLine("Completed")
);
Console.WriteLine("Done");
Console.ReadKey();
}
}
}
If I understand the book correctly, this should write a sequence of numbers to the console, once every five seconds forever since I never Dispose() of the sequence.
However, when I run the code, all I get is the "Done" at the end. No numbers, no "completed", nothing but "Done".
What am I doing wrong here?
I am assuming you haven't had the patience to wait for 5 seconds to elapse otherwise you would have seen that the code is working.
The main idea to keep in mind with Rx is that Observable.Subscribe will return control to calling method almost immediately. In other words, Observable.Subscribe does not block until the results are produced. Thus the call to Console.WriteLine will be invoked only after five seconds.
You need some way to make the main thread wait for what you are doing. You can use a semaphore if you like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LearningReactiveExtensions
{
public class Program
{
static void Main(string[] args)
{
SemaphoreSlim ss = new SemaphoreSlim(1);
var observable = Observable.Interval(TimeSpan.FromSeconds(5));
observable.Subscribe(
Console.WriteLine,
() => {
Console.WriteLine("Completed");
ss.Release();
}
);
ss.Wait();
Console.WriteLine("Done");
Console.ReadKey();
}
}
}
Though probably better in this case just to write
static void Main(string[] args)
{
SemaphoreSlim ss = new SemaphoreSlim(1);
Observable.Interval(TimeSpan.FromSeconds(5)).Wait();
Console.WriteLine("Completed");
Console.WriteLine("Done");
Console.ReadKey();
}

Unity TCP Server Hang Unity scene

I am trying to implement a TCP server in unity. I am using unity pro 3.5 and when I run this code in a scene, then unity hang, no response at all untill I kill it with Task Manager.
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;
public class Server : MonoBehaviour {
private IPAddress ipAd;
public string IP="127.0.0.1";
public int port = 8001;
private Socket s;
void Update ()
{
}
// Use this for initialization
void Awake () {
port = 8001;
ipAd = IPAddress.Parse(IP);
msg = "Listening at " + IP + ":" + port.ToString();
this.s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.s.Bind(new IPEndPoint(ipAd,port));
this.s.Listen(200);
while (true)
this.ReceiveMessage(this.s.Accept()); //hang if this line activated
}
private void ReceiveMessage(Socket socket)
{
byte[] tempbuffer = new byte[10000];
socket.Receive(tempbuffer);
rec.AssignFromByteArray(tempbuffer);
}
}
Server should run in it's own thread so the GameLoop can continue even if tcp_Listener.AcceptSocket() is a blocking call.
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class Server : MonoBehaviour {
private bool mRunning;
public static string msg = "";
public Thread mThread;
public TcpListener tcp_Listener = null;
void Awake() {
mRunning = true;
ThreadStart ts = new ThreadStart(Receive);
mThread = new Thread(ts);
mThread.Start();
print("Thread done...");
}
public void stopListening() {
mRunning = false;
}
void Receive() {
tcp_Listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8001);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
// check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(100);
}
else {
Socket ss = tcp_Listener.AcceptSocket();
BonePos rec = new BonePos();
byte[] tempbuffer = new byte[10000];
ss.Receive(tempbuffer); // received byte array from client
rec.AssignFromByteArray(tempbuffer); // my own datatype
}
}
}
void Update() {
}
void OnApplicationQuit() { // stop listening thread
stopListening();// wait for listening thread to terminate (max. 500ms)
mThread.Join(500);
}
}
See Related answer from answers.unity3d.com
You get the hanging because of this:
while (true)
this.ReceiveMessage(this.s.Accept()); //hang if this line activated
The entire process is stuck in this loop, so nothing else gets processed.
What you could do (though I would not recommend it) is to perform the action inside update() instead of an infinite loop.
what I suggest is to use something else to run your server instead of unity.
If you are creating a game server, you can use PUN (Photon Unity Networking) or write a standalone server in C#, or even an open-sourced server in python that matches your needs.
You have to get rid of this statement:
while (true)
this.ReceiveMessage(this.s.Accept());
And your server has to run in his own thread.
Unity's engine is single threaded, and the life cycle methods of monobehaviours run synchronously in a predefined order. An infinite loop in one life cycle method will infinitely hang the program.
Coroutines are one way that you can create infinite loops without hanging indefinitely. This use case would likely make use of WaitForSeconds