Межпроцессное взаимодействие
POST https://you_server_api/api/power
{
"mode": "on"
}
var baseAdress = new Uri(Properties.Settings.Default.BaseUri);
var server = new WebApiServer(baseAdress);
server.Start();
var message = $"Web API Self hosted on {baseAdress} Hit ENTER to exit...";
_logger.Info(message);
System.Console.ReadLine();
server.Stop();
return (int)ScanerStatus.Ok;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace RO.WebScaner.Console
{
/// <summary>
/// Web api server implementation
/// </summary>
public class WebApiServer
{
Logger _logger = LogManager.GetCurrentClassLogger();
Uri _uri;
HttpSelfHostServer _server;
/// <summary>
/// Create instance of Webapi embedd server
/// </summary>
/// <param name="uri">Endpoint address</param>
public WebApiServer(Uri uri)
{
_uri = uri;
}
/// <summary>
/// Start web api server.
/// </summary>
/// Команда для запуска исключения файрвола
/// netsh http add urlacl url=http://+:8000/ user=ZOOPLAZA-PC\developer
/// <remarks>
/// </remarks>
public void Start()
{
_logger.Info("Start WebApi server");
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_uri);
config.EnableCors();
ConfigRoutes(config);
ConfigFormatter(config);
_server = new HttpSelfHostServer(config);
_server.OpenAsync().Wait();
}
/// <summary>
/// Remove xml formatter, maybe in future add binary formatter
/// </summary>
/// <param name="config"></param>
private static void ConfigFormatter(HttpSelfHostConfiguration config)
{
// remove xml
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
/// <summary>
/// Config web api routes
/// </summary>
/// <param name="config"></param>
private static void ConfigRoutes(HttpSelfHostConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
public void Stop() {
_server.CloseAsync().Wait();
_logger.Info("Close WebApi server");
}
}
}
using NLog;
using RO.WebScaner.Console.Models;
using RO.WebScaner.Core;
using RO.WebScaner.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
namespace RO.WebScaner.Console.Controllers
{
public class ListController : ApiController
{
Logger _logger;
/// <summary>
/// Logger with delay load
/// </summary>
public Logger Logger
{
get
{
if (_logger == null)
{
_logger = LogManager.GetCurrentClassLogger();
}
return _logger;
}
set { _logger = value; }
}
[EnableCors(origins: "*",headers: "*", methods:"*")]
public IHttpActionResult Get()
{
try
{
var model = Worker.List();
return Ok(model);
}
catch(Exception e)
{
Logger.Error(e);
return InternalServerError(e);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Лямбда_Выражения
{
class Program
{
static void Main(string[] args)
{
Data data = new Data();
Test test = new Test();
Question question = new Question();
Answer answer = new Answer();
Answer answer2 = new Answer();
question.ТекстВопроса = "Сколько будет 2+2 ?";
answer.ТекстОтвета = "5";
answer.ОтветВерный = false;
answer2.ТекстОтвета = "4";
answer2.ОтветВерный = true;
question.Ответы.Add(answer);
question.Ответы.Add(answer2);
test.Вопросы.Add(question);
test.ДатаВремяСоздания = DateTime.Now;
test.Название = "Тест на знание математики";
test.Создатель = "SlNik";
data.Тесты.Add(test);
data.Сохранить();
Console.ReadKey();
}
}
[Serializable]
public class Answer
{
public string ТекстОтвета { get; set; }
public bool ОтветВерный { get; set; }
}
[Serializable]
public class Question
{
public Question()
{
Ответы = new List<Answer>();
}
public string ТекстВопроса { get; set; }
public List<Answer> Ответы { get; set; }
}
[Serializable]
public class Test
{
public Test()
{
Вопросы = new List<Question>();
}
public string Название { get; set; }
public string Создатель { get; set; }
public DateTime ДатаВремяСоздания { get; set; }
public List<Question> Вопросы { get; set; }
}
[Serializable]
public class Data
{
public List<Test> Тесты;
public string Patch = Path.Combine(Environment.CurrentDirectory, "Data.xml");
public Data()
{
Тесты = new List<Test>();
}
public Data(string patch = null)
{
Patch = patch;
if (Patch == null)
Patch = Path.Combine(Environment.CurrentDirectory, "Data.xml");
if (File.Exists(Patch))
Загрузить(Patch);
}
public void Загрузить(string patch)
{
XmlSerializer formatter = new XmlSerializer(typeof(Data));
using (FileStream fs = new FileStream(patch, FileMode.OpenOrCreate))
{
Data data = (Data)formatter.Deserialize(fs);
Console.WriteLine("Данные с тестами загружены");
Console.WriteLine("Кол-во тестов:{0}", data.Тесты.Count);
}
}
public void Сохранить(string patch = null)
{
if (patch == null)
patch = Patch;
XmlSerializer formatter = new XmlSerializer(typeof(Data));
using (FileStream fs = new FileStream(patch, FileMode.Create))
{
formatter.Serialize(fs, this);
Console.WriteLine("Объект сериализован");
}
}
}
}
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table WHERE test='%(test)s'", {"test": "123"})
myresult = mycursor.fetchone()
if myresult:
print(myresult)
else:
print("No records")
ManagementObjectSearcher searcher
= new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");
// или new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
string graphicsCard = string.Empty;
foreach (ManagementObject mo in searcher.Get())
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name == "Description")
{
graphicsCard = property.Value.ToString();
}
}
}
using System.Reflection;
Build Action
, значение Embedded Resource
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}