public bool LoadFromPath(string path) { BinaryFormatter formatter = new BinaryFormatter(); FileStream fs = new FileStream(path, FileMode.Open); try { ItemListArchive sdata = (ItemListArchive)formatter.Deserialize(fs); Item = sdata.Items; Man = sdata.Mans; LastPath = path; return(true); } catch (Exception ex) { Interaction.MsgBox("Не удается десериализовать: " + ex.Message); } fs.Close(); return(false); }
private void LoadDb(string path) { BinaryFormatter formatter = new BinaryFormatter(); formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; try { using (FileStream fs = new FileStream(path, FileMode.Open)) { ItemListArchive tmp = (ItemListArchive)formatter.Deserialize(fs); App.Db.Item = tmp.Items; App.Db.Man = tmp.Mans; //Interaction.MsgBox(tmp.Items.First().Name); Close(); } } catch (Exception ex) { Interaction.MsgBox("Не удается подгрузить: " + ex.Message); } }
public ServerDataShare() { if (!IsInitComplete) { listener = new HttpListener(); try { listener.Prefixes.Add("http://*:88/"); //http://localhost:8080/ listener.Start(); } catch (HttpListenerException) { //Задать запись в реестр для раздачи порта ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe"); startInfo.Verb = "runas"; startInfo.Arguments = "/c echo 'Нет разрешения на раздачу данных по http. Выполнение этих комманд исправит проблему...'&netsh http add urlacl url=http://*:88/ user="******"'", "\"") + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "&echo 'Если выполнение этих комманд было неудачно, то обратитесь к вашему системному администратору! Программу нужно перезапустить... Для удаления этой настройки введите комманду netsh http delete urlacl url=http://*:80/'&pause".Replace("'", "\"") + "&taskkill /f /im " + Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName) + "&start " + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; try { Process.Start(startInfo); } catch (Exception ex) { Interaction.MsgBox("Фаервол блокирует порт 80. Программа не может автоматически исправить проблему. Обратитесь к администратору. Ошибка " + ex.Message); } return; } //Инициализирует обработку запросов в новом потоке Task.Run(() => { while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; NameValueCollection parameters = request.QueryString; if (!string.IsNullOrWhiteSpace(parameters["Getlist"])) { Task.Factory.StartNew((ctx) => { BinaryFormatter formatter = new BinaryFormatter(); formatter.Binder = new ServerToClientNameConverter(); formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; ItemListArchive data = new ItemListArchive(App.SData.Items.ToArray(), App.SData.Mans.ToArray()); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, data); WriteBinary((HttpListenerContext)ctx, ms); ms.Close(); }, context, TaskCreationOptions.LongRunning); continue; } else if (!string.IsNullOrWhiteSpace(parameters["UploadProject"])) { Task.Factory.StartNew((ctx) => { BinaryFormatter formatter = new BinaryFormatter(); formatter.Binder = new ServerToClientNameConverter(); formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; try { Project proj = (Project)formatter.Deserialize(context.Request.InputStream); WriteText((HttpListenerContext)ctx, App.SData.AddProject(proj)); } catch (Exception ex) { WriteText((HttpListenerContext)ctx, "<error>" + ex.Message + "</error>"); } }, context, TaskCreationOptions.LongRunning); continue; } else if (!string.IsNullOrWhiteSpace(parameters["Project"])) { Task.Factory.StartNew((ctx) => { BinaryFormatter formatter = new BinaryFormatter(); formatter.Binder = new ServerToClientNameConverter(); formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; try { Project proj = App.SData.Projects[parameters["Project"]]; if (proj == null) { WriteText((HttpListenerContext)ctx, "<error>Project not found!</error>"); } MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, proj); WriteBinary((HttpListenerContext)ctx, ms); ms.Close(); } catch (Exception ex) { WriteText((HttpListenerContext)ctx, "<error>" + ex.Message + "</error>"); } }, context, TaskCreationOptions.LongRunning); continue; } else if (!string.IsNullOrWhiteSpace(parameters["GetItems"])) { Task.Factory.StartNew((ctx) => { try { MemoryStream stream = new MemoryStream(); DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Item[])); List <Item> tmp = new List <Item>(); for (int i = Int32.Parse(parameters["From"]); i < Int32.Parse(parameters["To"]); i++) { tmp.Add(App.SData.Items[i]); } jsonFormatter.WriteObject(stream, tmp.ToArray()); Interaction.MsgBox(stream.Length); stream.Position = 0; StreamReader sr = new StreamReader(stream); Console.Write("JSON form of Person object: "); WriteText((HttpListenerContext)ctx, sr.ReadToEnd()); } catch (Exception ex) { WriteText((HttpListenerContext)ctx, "<error>" + ex.Message + "</error>"); } }, context, TaskCreationOptions.LongRunning); continue; } else { Task.Factory.StartNew((ctx) => { BinaryFormatter formatter = new BinaryFormatter(); WriteText((HttpListenerContext)ctx, "<error>Check your parameters</error>"); }, context, TaskCreationOptions.LongRunning); continue; } } }); } else { throw new Exception("Уже инициализированно! Обращайтесь через App!"); } }