Here are the examples of the csharp api System.Convert.ToInt32(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2673 Examples
19
Source : FaceDancer.cs
with MIT License
from 001SPARTaN
with MIT License
from 001SPARTaN
static void Main(string[] args)
{
int procId;
string file;
if (args.Length < 2)
{
file = "whoami /priv";
if (args.Length == 0)
{
// If we don't have a process ID as an argument, find winlogon.exe
procId = Process.GetProcessesByName("winlogon").First().Id;
}
else if (args[0].Contains('.'))
{
procId = Process.GetProcessesByName("winlogon").First().Id;
if (args != null)
{
file = args[0];
}
}
else
{
procId = Convert.ToInt32(args[0]);
}
}
else
{
procId = Convert.ToInt32(args[0]);
file = args[1];
}
Console.WriteLine("Stealing token from PID " + procId);
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupHandle = IntPtr.Zero;
SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
Console.WriteLine("Process handle: True");
bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
Console.WriteLine("OpenProcessToken: " + procToken);
bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero,
(uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
Console.WriteLine("Impersonated user: " + ident.Name);
STARTUPINFO startInfo = new STARTUPINFO();
PipeSecurity sec = new PipeSecurity();
sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));
using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
{
using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
{
// Set process to use anonymous pipe for input/output
startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
// END NAME PIPE INITIALIZATION
PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
using (StreamReader reader = new StreamReader(pipeServer))
{
bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
Process proc = Process.GetProcessById(newProc.dwProcessId);
while (!proc.HasExited)
{
Thread.Sleep(1000);
}
pipeClient.Close();
string output = reader.ReadToEnd();
Console.WriteLine("Started process with ID " + newProc.dwProcessId);
Console.WriteLine("CreateProcess return code: " + createProcess);
Console.WriteLine("Process output: " + output);
}
CloseHandle(tokenHandle);
CloseHandle(dupHandle);
}
}
}
19
Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5
with GNU General Public License v3.0
from 0x2b00b1e5
public static XmlSettings ReadSettings()
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.xml");
if (!File.Exists(path))
{
throw new FileNotFoundException("The settings file was not found on it's desired location!");
}
// Get all settings as strings
System.Xml.XmlDoreplacedent d = XMLParser.LoadDoreplacedent(path);
string ClientID = XMLParser.FindByTag("ClientID", d)[0];
string Pipe = XMLParser.FindByTag("Pipe", d)[0];
string Secret = XMLParser.FindByTag("SecretProject", d)[0];
string DebugLevel = XMLParser.FindByTag("DebugLevel", d)[0];
string SecretMessage = XMLParser.FindByTag("SecretMessage", d)[0];
string NoNameMessage = XMLParser.FindByTag("NoNameMessage", d)[0];
string interval = XMLParser.FindByTag("RefreshInterval", d)[0];
string accWarn = XMLParser.FindByTag("WarningAccepted", d)[0];
// Convert, store and return
XmlSettings setting = new XmlSettings();
setting.ClientID = ClientID;
setting.Pipe = Convert.ToInt32(Pipe);
setting.Secret = Convert.ToBoolean(Secret);
setting.SecretMessage = SecretMessage;
setting.NoNameMessage = NoNameMessage;
setting.RefeshInterval = Convert.ToInt32(interval);
setting.AcceptedWarning = Convert.ToBoolean(accWarn);
switch (Convert.ToInt32(DebugLevel))
{
case 0:
setting.logLevel = LogLevel.Info;
break;
case 1:
setting.logLevel = LogLevel.Warning;
break;
case 2:
setting.logLevel = LogLevel.Error;
break;
case 3:
setting.logLevel = LogLevel.None;
break;
}
return setting;
}
19
Source : MetroColorPicker.xaml.cs
with MIT License
from 1217950746
with MIT License
from 1217950746
private int ConvertInt(string text)
{
try
{
return Convert.ToInt32(text);
}
catch
{
return -1;
}
}
19
Source : SettingForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void buttonSave_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Checked)
{
AppConfig.Instance.MConfig.SkinIndex = Convert.ToInt32(item.Tag.ToString());
break;
}
}
AppConfig.Instance.SaveConfig(1);
this.Close();
}
19
Source : SftpForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void TransfersFileProgress(string id, long precent, long c, long max, int elapsed)
{
try
{
int start = 0, end = Convert.ToInt32(DateTime.Now.ToString("ffff"));
if(TIMEDIC.ContainsKey(id)){
start = TIMEDIC[id];
TIMEDIC[id] = end;
} else {
TIMEDIC.Add(id, end);
}
long startByte = 0, endByte = c;
if (BYTEDIC.ContainsKey(id))
{
startByte = BYTEDIC[id];
BYTEDIC[id] = endByte;
} else {
BYTEDIC.Add(id, endByte);
}
this.BeginInvoke((MethodInvoker)delegate()
{
TransferItem obj = null;
foreach (ListViewItem item in listView3.Items)
{
if (item.Name == id)
{
obj = (TransferItem)item.Tag;
obj.Progress = precent;
item.SubItems[1].Text = TransferStatus.Transfers.ToString();
item.SubItems[2].Text = precent + "%";
item.SubItems[6].Text = Utils.CalculaSpeed(startByte, endByte, max, start, end);
item.SubItems[7].Text = Utils.CalculaTimeLeft(startByte, endByte, max, start, end);
break;
}
}
});
}
catch(Exception ex) {
logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
ChangeTransferItemStatus("R2L", id, TransferStatus.Failed);
}
}
19
Source : SftpForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void toolStripButton7_Click(object sender, EventArgs e)
{
string host = text_host.Text;
string username = text_username.Text;
string preplaced = text_preplaced.Text;
string port = text_port.Text;
IPAddress ip;
if (IPAddress.TryParse(host, out ip))
{
if(string.IsNullOrWhiteSpace(username)){
MessageBox.Show(this, "请输入用户名");
}
else if (string.IsNullOrWhiteSpace(preplaced))
{
MessageBox.Show(this, "请输入密码");
}
else if (string.IsNullOrWhiteSpace(port))
{
MessageBox.Show(this, "请输入端口号");
}
else
{
user.Host = host;
user.UserName = username;
user.Preplacedword = YSEncrypt.EncryptA(preplaced, KeysUtil.PreplacedKey);
user.Port = Convert.ToInt32(port);
LoadRightForm(user);
}
}
else
{
MessageBox.Show(this, "Host地址不正确");
}
}
19
Source : Program.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
[STAThread]
static void Main(string[] args)
{
if (null != args && args.Length > 3)
{
initUser = new SshUser();
initUser.Host = args[0];
initUser.UserName = args[1];
initUser.Preplacedword = args[2];
initUser.Port = Convert.ToInt32(args[3]);
}
/*AllocConsole();
windowHandle = FindWindow(null, Process.GetCurrentProcess().MainModule.FileName);
IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
uint SC_CLOSE = 0xF060;
RemoveMenu(closeMenu, SC_CLOSE, 0x0);
SetConsolereplacedle("调试信息");*/
try
{
//处理未捕获的异常
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MAIN = new MainForm();
Application.Run(MAIN);
//Application.Run(new SftpForm(initUser));
}
catch (Exception ex)
{
string str = GetExceptionMsg(ex, string.Empty);
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//FreeConsole();
}
19
Source : PlyHandler.cs
with MIT License
from 3DBear
with MIT License
from 3DBear
private static List<int> GetTriangles(string faceVertexList, PlyHeader header)
{
switch (header.FaceParseMode)
{
case PlyFaceParseMode.VertexCountVertexIndex:
var split = faceVertexList.Split(' ');
var count = Convert.ToInt32(split.First());
switch (count)
{
case 3: // triangle
return split.ToList().GetRange(1, 3).Select(x => Convert.ToInt32(x)).ToList();
case 4: // face
var triangles = new List<int>();
var indices = split.ToList().GetRange(1, 4).Select(x => Convert.ToInt32(x)).ToList();
triangles.AddRange(QuadToTriangles(indices));
return triangles;
default:
Debug.LogWarning("Warning: Found a face with more than 4 vertices, skipping...");
return new List<int>();
}
default:
Debug.LogWarning("Ply GetTriangles: Unknown parse mode");
return new List<int>();
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
static void Main(string[] args)
{
if (args.Length != 5)
ShowUsage();
else
{
try
{
Options.Host = args[0];
Options.Port = Convert.ToInt32(args[1]);
Options.Username = args[3];
if (args[2] == "plaintext")
Options.Preplacedword = args[4];
else if (args[2] == "ntlmhash")
Options.hash = args[4];
else
{
Console.WriteLine("[!] Wrong parameter");
System.Environment.Exit(0);
}
Network.Connect(Options.Host, Options.Port);
MCS.sendConnectionRequest(null, false);
}
catch (Exception exception)
{
Console.WriteLine("[!] " + exception.Message);
Console.WriteLine("InnerException: " + exception.InnerException);
}
}
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
//ILRuntime doesn't support nullable valuetype
Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
Type value_type = inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClreplaced || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType();
var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;
if (vt.IsreplacedignableFrom(json_type))
return reader.Value;
if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
{
if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
return reader.Value;
}
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
custom_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
base_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe it's an enum
if (vt.IsEnum)
return Enum.ToObject (vt, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (vt, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
{
item = (int) item;
}
else
{
item = rt.CheckCLRTypes(item);
}
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
if (value_type is ILRuntime.Reflection.ILRuntimeType)
instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
else
instance = Activator.CreateInstance(value_type);
bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string key = (string) reader.Value;
if (t_data.Properties.ContainsKey(key))
{
PropertyMetadata prop_data =
t_data.Properties[key];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(
instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(
instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format(
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, key));
}
else
{
ReadSkip(reader);
continue;
}
}
var dict = ((IDictionary) instance);
var elem_type = t_data.ElementType;
object readValue = ReadValue(elem_type, reader);
var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
: t_data.ElementType;
//value 是枚举的情况没处理,毕竟少
if (isIntKey)
{
var dictValueType = value_type.GetGenericArguments()[1];
IConvertible convertible = dictValueType as IConvertible;
if (convertible == null)
{
//自定义类型扩展
if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
{
var v = Convert.ChangeType(readValue.ToString(), dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(Convert.ToInt32(key), readValue);
// throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
}
}
else
{
var v = Convert.ChangeType(readValue, dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(key, readValue);
}
}
}
}
return instance;
}
19
Source : HotKeys.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public static void LoadHotKeys()
{
hotkeyCode.Clear();
hotkeyDescription.Clear();
if (!File.Exists(HotKeyFile))
{
MainWindow.Logger.Error("Hotkey file not found, going to create default");
CheckCreateFile.CreateDefaultXML();
}
XmlReader r = XmlReader.Create(HotKeyFile); // "hotkeys.xml");
while (r.Read())
{
if (!r.IsStartElement())
continue;
switch (r.Name)
{
case "Hotkeys":
// Get Hotkey Version Number, used for modifying or updating to newer hotkey files (ie if new features are added)
if (r["HotkeyFileVer"].Length > 0)
{
CurrentHotKeyFileVersion = Convert.ToInt32(r["HotkeyFileVer"]); // Current Hotkey File Version
}
break;
case "bind":
if ((r["keyfunction"].Length > 0) && (r["keycode"] != null))
{
if (!hotkeyCode.ContainsKey(r["keyfunction"]))
hotkeyCode.Add(r["keyfunction"], r["keycode"]);
hotkeyDescription.Add(r["keyfunction"], r["key_description"]);
}
break;
}
}
r.Close();
// Check if CurrentFileVersion and NewFileVersion is different and if so, Update the file then reload by running ths process again.
MainWindow.Logger.Info("Hotkey file found, checking if needing update/modification");
if (CurrentHotKeyFileVersion < CheckCreateFile.HotKeyFileVer) // If CurrentHotKeyFileVersion does not equal HotKeyFileVer then update is required
{
CheckCreateFile.CheckAndUpdateXMLFile(CurrentHotKeyFileVersion);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static void Main(string[] args)
{
try
{
logo();
// https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10
var arguments = new Dictionary<string, string>();
foreach (var argument in args)
{
var idx = argument.IndexOf(':');
if (idx > 0)
arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
else
arguments[argument] = string.Empty;
}
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
}
else
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
}
if (arguments.Count == 0)
{
Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
help();
}
else if (arguments.ContainsKey("/pname"))
{
Process[] process = Process.GetProcessesByName(arguments["/pname"]);
if (process.Length > 0)
{
for (int i = 0; i < process.Length; i++)
{
Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
}
}
else
{
Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
}
}
else if (arguments.ContainsKey("/pid"))
{
int procid = Convert.ToInt32(arguments["/pid"]);
Process process = Process.GetProcessById(procid);
Console.WriteLine($"[+] Dumping {process.ProcessName} process");
Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
dump(process.Handle, (uint)process.Id, process.ProcessName);
}
else
{
Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
help();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
19
Source : SolarUtil.cs
with MIT License
from 6tail
with MIT License
from 6tail
public static int getWeeksOfMonth(int year, int month, int start)
{
int days = getDaysOfMonth(year, month);
DateTime firstDay = ExactDate.fromYmd(year, month, 1);
int week = Convert.ToInt32(firstDay.DayOfWeek.ToString("d"));
return (int)Math.Ceiling((days + week - start) * 1D / WEEK.Length);
}
19
Source : Solar.cs
with MIT License
from 6tail
with MIT License
from 6tail
public int getWeek()
{
return Convert.ToInt32(calendar.DayOfWeek.ToString("d"));
}
19
Source : SolarWeek.cs
with MIT License
from 6tail
with MIT License
from 6tail
public int getIndex()
{
DateTime firstDay = ExactDate.fromYmd(year, month, 1);
int firstDayWeek = Convert.ToInt32(firstDay.DayOfWeek.ToString("d"));
if (firstDayWeek == 0)
{
firstDayWeek = 7;
}
return (int)Math.Ceiling((day + firstDayWeek - start) * 1D / SolarUtil.WEEK.Length);
}
19
Source : SolarWeek.cs
with MIT License
from 6tail
with MIT License
from 6tail
public Solar getFirstDay()
{
DateTime c = ExactDate.fromYmd(year, month, day);
int week = Convert.ToInt32(c.DayOfWeek.ToString("d"));
int prev = week - start;
if (prev < 0)
{
prev += 7;
}
c = c.AddDays(-prev);
return new Solar(c);
}
19
Source : NpcCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
{
try
{
var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于
var fieldProp = GetFieldPropertyInfo(player, field);
if (fieldProp == null)
{
return false;
}
var objectValue = fieldProp.GetValue(player);
var typeCode = Type.GetTypeCode(fieldProp.GetType());
switch (typeCode)
{
case TypeCode.Int32:
return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));
case TypeCode.Int64:
return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));
case TypeCode.Decimal:
return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));
case TypeCode.Double:
return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));
case TypeCode.Boolean:
return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));
case TypeCode.DateTime:
return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));
case TypeCode.String:
return relations.Contains(strValue.CompareTo(objectValue));
default:
throw new Exception($"不支持的数据类型: {typeCode}");
}
}
catch (Exception ex)
{
_logger.LogError($"CheckField Exception:{ex}");
return false;
}
}
19
Source : Program.cs
with MIT License
from 8bitbytes
with MIT License
from 8bitbytes
private static void processCommand(string command)
{
var fgRestore = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
var cmdPart = command.Split(" ");
switch (cmdPart[0])
{
case "command":
{
Console.WriteLine("Ready to start accepting commands");
break;
}
case "takeoff":
{
Console.WriteLine("Initiating auto take off");
break;
}
case "land":
{
Console.WriteLine("Initiating auto landing");
break;
}
case "up":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move up. Up value not provided");
break;
}
Console.WriteLine($"Moving aricraft up {cmdPart[1]} cm");
break;
}
case "down":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move down. down value not provided");
break;
}
Console.WriteLine($"Moving aricraft down {cmdPart[1]} cm");
break;
}
case "left":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move left. Left value not provided");
break;
}
Console.WriteLine($"Moving aricraft left {cmdPart[1]} cm");
break;
}
case "right":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move right. Right value not provided");
break;
}
Console.WriteLine($"Moving aricraft right {cmdPart[1]} cm");
break;
}
case "forward":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move forward. Forward value not provided");
break;
}
Console.WriteLine($"Moving aricraft forward {cmdPart[1]} cm");
break;
}
case "back":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move back. Back value not provided");
break;
}
Console.WriteLine($"Moving aricraft back {cmdPart[1]} cm");
break;
}
case "cw":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot rotate clockwise. Degree value not provided");
break;
}
Console.WriteLine($"Moving aricraft clockwise {cmdPart[1]} degrees");
break;
}
case "ccw":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot rotate counter-clockwise. Degree value not provided");
break;
}
Console.WriteLine($"Moving aricraft counter-clockwise {cmdPart[1]} degrees");
break;
}
case "flip":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot flip. Flip direction not provided");
break;
}
Console.WriteLine($"Flipping aricraft {cmdPart[1]}");
break;
}
case "speed":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot set speed. Speed not provided");
break;
}
speed = Convert.ToInt32(cmdPart[1]);
Console.WriteLine($"Setting aircraft speed to {cmdPart[1]} cm/s");
break;
}
}
Console.ForegroundColor = fgRestore;
}
19
Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count == 0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
//int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
//int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
//float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]); // 1.1
//bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
int maximumDeptOfReconstructionSurfaceTree = 8;
int targetWidthOfTheFinestLevelOctree = 0;
double ratioBetweenReconCubeAndBBCubeStd = 1.1;
bool ReconstructorUsingLinearInterpolation = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
DA.GetData(7, ref ReconstructorUsingLinearInterpolation);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count==0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : HTTP.cs
with MIT License
from 944095635
with MIT License
from 944095635
private void SetProxy(HttpItem item)
{
bool isIeProxy = false;
if (!string.IsNullOrWhiteSpace(item.ProxyIp))
{
isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
}
if (!string.IsNullOrWhiteSpace(item.ProxyIp) && !isIeProxy)
{
//设置代理服务器
if (item.ProxyIp.Contains(":"))
{
string[] plist = item.ProxyIp.Split(':');
WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
//建议连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当前请求对象
request.Proxy = myProxy;
}
else
{
WebProxy myProxy = new WebProxy(item.ProxyIp, false);
//建议连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当前请求对象
request.Proxy = myProxy;
}
}
else if (isIeProxy)
{
//设置为IE代理
}
else
{
request.Proxy = item.WebProxy;
}
}
19
Source : PickPanel.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
private static void ItemClicked(string btnName)
{
int itemIdx = Convert.ToInt32(btnName.Split('_')[1]);
LogDebug(itemIdx);
HeroController.instance.StartCoroutine(WaitFrame());
IEnumerator WaitFrame()
{
yield return new WaitForEndOfFrame();
Focus(itemIdx);
}
}
19
Source : Program.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
static WorkbookEditor cmd_ModifyLabel(WorkbookEditor wbe)
{
List<Lbl> existingLbls = wbe.WbStream.GetAllRecordsByType<Lbl>();
log("\t[+] Detect {0} Labels ...\n", ConsoleColor.Yellow, existingLbls.Count);
for (int i = 0; i < existingLbls.Count; i++)
{ // XLUnicodeStringNoCch
var labelName = existingLbls[i].IsAutoOpenLabel() ? "Auto_Open" : existingLbls[i].Name.Value;
log("\t\t[{0}] {1:s}\n", ConsoleColor.Yellow, i, labelName);
}
log("\t[?] which one to midify (index): ", ConsoleColor.Yellow);
try
{
int indx = Convert.ToInt32(Console.ReadLine());
var labelName = existingLbls[indx].IsAutoOpenLabel() ? "Auto_Open" : existingLbls[indx].Name.Value;
log("\t[v] select label `{0}`\n", ConsoleColor.Yellow, labelName);
log("\t\t[1] hide label\n", ConsoleColor.Yellow);
log("\t\t[2] obfuscate label\n", ConsoleColor.Yellow);
log("\t[?] choose action (index): ", ConsoleColor.Yellow);
var replaceLabelStringLbl = ((BiffRecord)existingLbls[indx].Clone()).AsRecordType<Lbl>();
switch (Convert.ToInt32(Console.ReadLine())) {
case 1:
replaceLabelStringLbl.fHidden = true;
wbe.WbStream = wbe.WbStream.ReplaceRecord(existingLbls[indx], replaceLabelStringLbl);
wbe.WbStream = wbe.WbStream. FixBoundSheetOffsets();
historyList.Add(string.Format("[#] History - label `{0}` vanish!\n", labelName));
break;
case 2:
replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(getObfscuteName(labelName), true));
replaceLabelStringLbl.fBuiltin = false;
wbe.WbStream = wbe.WbStream.ReplaceRecord(existingLbls[indx], replaceLabelStringLbl);
wbe.WbStream = wbe.WbStream.FixBoundSheetOffsets();
historyList.Add(string.Format("[#] History - obfuscate `{0}` done!\n", labelName));
break;
}
}
catch (Exception) {}
return wbe;
}
19
Source : Program.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
static WorkbookEditor cmd_ModifySheet(WorkbookEditor wbe)
{
List<BoundSheet8> sheetList = wbe.WbStream.GetAllRecordsByType<BoundSheet8>();
log("\t[+] Detect {0} Sheets ...\n", ConsoleColor.Yellow, sheetList.Count);
for (int i = 0; i < sheetList.Count; i++)
log("\t\t[{0}] {1:s}\n", ConsoleColor.Yellow, i, sheetList[i].stName.Value);
log("\t[?] which one to hide (index): ", ConsoleColor.Yellow);
try
{
int indx = Convert.ToInt32(Console.ReadLine());
var replaceSheet = ((BiffRecord)sheetList[indx].Clone()).AsRecordType<BoundSheet8>();
replaceSheet.hsState = BoundSheet8.HiddenState.SuperVeryHidden;
wbe.WbStream = wbe.WbStream.ReplaceRecord(sheetList[indx], replaceSheet);
wbe.WbStream = wbe.WbStream.FixBoundSheetOffsets();
historyList.Add(string.Format("[#] History - Hide Sheet `{0}` done!\n", sheetList[indx].stName.Value));
}
catch { }
return wbe;
}
19
Source : Program.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
static void Main(string[] args)
{
printMenu();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (args.Length < 1) {
log("usage: xlsKami.exe [path/to/xls]", ConsoleColor.Red);
return;
}
WorkbookEditor wbe;
try {
wbe = new WorkbookEditor(LoadDecoyDoreplacedent(args[0]));
}
catch (Exception e) {
log(e.Message, ConsoleColor.Red);
return;
}
for (bool bye = false; !bye; ) {
try {
printMenu(showMenu: true, loadXlsPath: args[0]);
switch (Convert.ToInt32(Console.ReadLine())) {
case 1:
log("[+] Enter Mode: Label Patching\n", ConsoleColor.Cyan);
wbe = cmd_ModifyLabel(wbe);
log("[+] Exit Mode\n", ConsoleColor.Cyan);
break;
case 2:
log("[+] Enter Mode: Sheet Patching\n", ConsoleColor.Cyan);
wbe = cmd_ModifySheet(wbe);
log("[!] Exit Mode\n", ConsoleColor.Cyan);
break;
case 3:
WorkbookStream createdWorkbook = wbe.WbStream;
ExcelDocWriter writer = new ExcelDocWriter();
string outputPath = args[0].Insert(args[0].LastIndexOf('.'), "_infect");
Console.WriteLine("Writing generated doreplacedent to {0}", outputPath);
writer.WriteDoreplacedent(outputPath, createdWorkbook, null);
bye = true;
break;
case 4:
bye = true;
break;
}
}
catch (Exception) { }
}
Console.WriteLine("Thanks for using xlsKami\nbye.\n");
}
19
Source : DataEntry.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void writeLeaderboardEntry(string leaderboardName, string value)
{
byte[] extraData = new byte[] { 0x54, 0x65, 0x73, 0x74 };
Leaderboards.WriteEntry(leaderboardName, Convert.ToInt32(value), extraData, false).OnComplete(leaderboardWriteCallback);
}
19
Source : MetaWeblogService .cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public async Task<bool> DeletePostAsync(string key, string postid, string username, string preplacedword, bool publish)
{
if (await IsValidMetaWeblogUserAsync(username, preplacedword))
{
var ExistingBlogs =
_BlazorBlogsContext.Blogs
.Where(x => x.BlogId == Convert.ToInt32(postid))
.FirstOrDefault();
if (ExistingBlogs != null)
{
_BlazorBlogsContext.Blogs.Remove(ExistingBlogs);
_BlazorBlogsContext.SaveChanges();
}
else
{
throw new Exception("Blog not found");
}
}
else
{
throw new Exception("Bad user name or preplacedword");
}
return true;
}
19
Source : MetaWeblogService .cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
public async Task<bool> EditPostAsync(string postid, string username, string preplacedword, Post post, bool publish)
{
if (await IsValidMetaWeblogUserAsync(username, preplacedword))
{
var ExistingBlogs = await
_BlazorBlogsContext.Blogs
.Include(x => x.BlogCategory)
.Where(x => x.BlogId == Convert.ToInt32(postid))
.FirstOrDefaultAsync();
if (ExistingBlogs != null)
{
try
{
if (post.dateCreated > Convert.ToDateTime("1/1/1900"))
{
ExistingBlogs.BlogDate =
post.dateCreated;
}
ExistingBlogs.Blogreplacedle =
post.replacedle;
ExistingBlogs.BlogContent =
post.description;
if (post.description != null)
{
string strSummary = ConvertToText(post.description);
int intSummaryLength = strSummary.Length;
if (intSummaryLength > 500)
{
intSummaryLength = 500;
}
ExistingBlogs.BlogSummary = strSummary.Substring(0, intSummaryLength);
}
if (post.categories == null)
{
ExistingBlogs.BlogCategory = null;
}
else
{
ExistingBlogs.BlogCategory =
GetBlogCategories(ExistingBlogs, post.categories);
}
_BlazorBlogsContext.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.GetBaseException().Message);
}
}
else
{
throw new Exception("Bad user name or preplacedword");
}
}
return true;
}
19
Source : UploadController.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
private int ConvertToInteger(string strParamVersion)
{
int intVersionNumber = 0;
string strVersion = strParamVersion;
// Split into parts seperated by periods
char[] splitchar = { '.' };
var strSegments = strVersion.Split(splitchar);
// Process the segments
int i = 0;
List<int> colMultiplyers = new List<int> { 10000, 100, 1 };
foreach (var strSegment in strSegments)
{
int intSegmentNumber = Convert.ToInt32(strSegment);
intVersionNumber = intVersionNumber + (intSegmentNumber * colMultiplyers[i]);
i++;
}
return intVersionNumber;
}
19
Source : BlogsService.cs
with MIT License
from ADefWebserver
with MIT License
from ADefWebserver
private List<BlogCategory> GetSelectedBlogCategories(BlogDTO objBlogs, IEnumerable<string> blogCatagories)
{
List<BlogCategory> colBlogCategory = new List<BlogCategory>();
foreach (var item in blogCatagories)
{
int intBlogCatagoryId = Convert.ToInt32(item);
// Get the Category
var Category = _context.Categorys
.Where(x => x.CategoryId == intBlogCatagoryId)
.AsNoTracking()
.FirstOrDefault();
// Create a new BlogCategory
BlogCategory NewBlogCategory = new BlogCategory();
NewBlogCategory.BlogId = objBlogs.BlogId;
NewBlogCategory.CategoryId = Category.CategoryId;
// Add it to the list
colBlogCategory.Add(NewBlogCategory);
}
return colBlogCategory;
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static List<object> LoadPossibleTreasures(string[] includeList, int minItemValue, int maxItemValue)
{
List<object> treasures = new List<object>();
int currentCount = 0;
if (includeList.Contains("MeleeWeapon"))
{
foreach (KeyValuePair<int, string> kvp in Game1.content.Load<Dictionary<int, string>>("Data\\weapons"))
{
if (Config.ForbiddenWeapons.Contains(kvp.Key))
continue;
int price = new MeleeWeapon(kvp.Key).salePrice();
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, "MeleeWeapon"));
}
//context.Monitor.Log($"Added {treasures.Count - currentCount} weapons");
currentCount = treasures.Count;
}
if (includeList.Contains("Shirt") || includeList.Contains("Pants"))
{
foreach (KeyValuePair<int, string> kvp in Game1.clothingInformation)
{
int price = 0;
if (includeList.Contains("Shirt") && kvp.Value.Split('/')[8].ToLower().Trim() == "shirt")
{
price = Convert.ToInt32(kvp.Value.Split('/')[5]);
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, "Shirt"));
}
else if (includeList.Contains("Pants") && kvp.Value.Split('/')[8].ToLower().Trim() == "pants")
{
price = Convert.ToInt32(kvp.Value.Split('/')[5]);
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, "Pants"));
}
else
continue;
}
//Monitor.Log($"Added {treasures.Count - currentCount} clothes");
currentCount = treasures.Count;
}
if (includeList.Contains("Hat"))
{
foreach (KeyValuePair<int, string> kvp in Game1.content.Load<Dictionary<int, string>>("Data\\hats"))
{
if (CanAddTreasure(1000, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, 1000, "Hat"));
}
//Monitor.Log($"Added {treasures.Count - currentCount} hats");
currentCount = treasures.Count;
}
if (includeList.Contains("Boots"))
{
foreach (KeyValuePair<int, string> kvp in Game1.content.Load<Dictionary<int, string>>("Data\\Boots"))
{
int price = Convert.ToInt32(kvp.Value.Split('/')[2]);
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, "Boots"));
}
//Monitor.Log($"Added {treasures.Count - currentCount} boots");
currentCount = treasures.Count;
}
if (includeList.Contains("BigCraftable"))
{
foreach (KeyValuePair<int, string> kvp in Game1.bigCraftablesInformation)
{
if (Config.ForbiddenBigCraftables.Contains(kvp.Key))
continue;
//int price = GetStorePrice(kvp.Key);
//if(price == 0)
int price = new Object(Vector2.Zero, kvp.Key, false).price;
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, "BigCraftable"));
}
//Monitor.Log($"Added {treasures.Count - currentCount} boots");
currentCount = treasures.Count;
}
foreach (KeyValuePair<int, string> kvp in Game1.objectInformation)
{
if (Config.ForbiddenObjects.Contains(kvp.Key))
continue;
if (kvp.Value.Split('/')[5] == "...")
continue;
string type = "";
int price = Convert.ToInt32(kvp.Value.Split('/')[1]);
if (includeList.Contains("Ring") && kvp.Value.Split('/')[3] == "Ring")
{
type = "Ring";
}
else if (includeList.Contains("Cooking") && kvp.Value.Split('/')[3].StartsWith("Cooking"))
{
type = "Cooking";
}
else if (includeList.Contains("Seed") && kvp.Value.Split('/')[3].StartsWith("Seeds"))
{
type = "Seed";
}
else if (includeList.Contains("Mineral") && kvp.Value.Split('/')[3].StartsWith("Mineral"))
{
type = "Mineral";
}
else if (includeList.Contains("Fish") && kvp.Value.Split('/')[3].StartsWith("Fish"))
{
type = "Fish";
}
else if (includeList.Contains("Relic") && kvp.Value.Split('/')[3].StartsWith("Arch"))
{
type = "Relic";
}
else if (includeList.Contains("BasicObject") && kvp.Value.Split('/')[3].StartsWith("Basic"))
{
type = "BasicObject";
}
else
continue;
if (CanAddTreasure(price, minItemValue, maxItemValue))
treasures.Add(new Treasure(kvp.Key, price, type));
}
//Monitor.Log($"Added {treasures.Count - currentCount} objects");
return treasures;
}
19
Source : CustomLocksPatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static bool GameLocation_lockedDoorWarp(GameLocation __instance, string[] actionParams)
{
try
{
if (Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason) && Utility.getStartTimeOfFestival() < 1900)
{
}
else if (actionParams[3].Equals("SeedShop") && Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth).Equals("Wed") && !Utility.HasAnyPlayerSeenEvent(191393))
{
if (ModEntry.Config.AllowSeedShopWed)
{
ModEntry.DoWarp(actionParams, __instance);
return false;
}
}
else if (
(Game1.timeOfDay < Convert.ToInt32(actionParams[4]) || Game1.timeOfDay >= Convert.ToInt32(actionParams[5]) && ModEntry.Config.AllowOutsideTime)
&&
(actionParams.Length >= 7 && !Game1.currentSeason.Equals("winter") && (!Game1.player.friendshipData.ContainsKey(actionParams[6]) || Game1.player.friendshipData[actionParams[6]].Points < Convert.ToInt32(actionParams[7])) && ModEntry.Config.AllowStrangerHomeEntry)
)
{
// both outside time and stranger
ModEntry.DoWarp(actionParams, __instance);
return false;
}
else if (
(Game1.timeOfDay >= Convert.ToInt32(actionParams[4]) && Game1.timeOfDay < Convert.ToInt32(actionParams[5]))
&&
(actionParams.Length >= 7 && !Game1.currentSeason.Equals("winter") && (!Game1.player.friendshipData.ContainsKey(actionParams[6]) || Game1.player.friendshipData[actionParams[6]].Points < Convert.ToInt32(actionParams[7])) && ModEntry.Config.AllowStrangerHomeEntry)
)
{
// inside time and stranger
ModEntry.DoWarp(actionParams, __instance);
return false;
}
else if (
(Game1.timeOfDay < Convert.ToInt32(actionParams[4]) || Game1.timeOfDay >= Convert.ToInt32(actionParams[5]) && ModEntry.Config.AllowOutsideTime)
&&
(actionParams.Length < 7 || Game1.currentSeason.Equals("winter") || (Game1.player.friendshipData.ContainsKey(actionParams[6]) && Game1.player.friendshipData[actionParams[6]].Points >= Convert.ToInt32(actionParams[7])))
)
{
// outside time and not stranger
ModEntry.DoWarp(actionParams, __instance);
return false;
}
else if (actionParams.Length < 7 && ModEntry.Config.AllowOutsideTime)
{
ModEntry.DoWarp(actionParams, __instance);
return false;
}
else if (ModEntry.Config.AllowStrangerHomeEntry)
{
ModEntry.DoWarp(actionParams, __instance);
return false;
}
return true;
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(GameLocation_lockedDoorWarp)}:\n{ex}", LogLevel.Error);
return true;
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
internal static void DoWarp(string[] actionParams, GameLocation instance)
{
Rumble.rumble(0.15f, 200f);
Game1.player.completelyStopAnimatingOrDoingAction();
instance.playSoundAt("doorClose", Game1.player.getTileLocation(), NetAudio.SoundContext.Default);
Game1.warpFarmer(actionParams[3], Convert.ToInt32(actionParams[1]), Convert.ToInt32(actionParams[2]), false);
}
19
Source : Familiar.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
protected void parseMonsterInfo(string name)
{
string[] monsterInfo = Game1.content.Load<Dictionary<string, string>>("Data\\Monsters")[name].Split(new char[]
{
'/'
});
Health = Convert.ToInt32(monsterInfo[0]);
MaxHealth = Health;
DamageToFarmer = Convert.ToInt32(monsterInfo[1]);
coinsToDrop.Value = Game1.random.Next(Convert.ToInt32(monsterInfo[2]), Convert.ToInt32(monsterInfo[3]) + 1);
isGlider.Value = Convert.ToBoolean(monsterInfo[4]);
durationOfRandomMovements.Value = Convert.ToInt32(monsterInfo[5]);
string[] objectsSplit = monsterInfo[6].Split(new char[]
{
' '
});
objectsToDrop.Clear();
for (int i = 0; i < objectsSplit.Length; i += 2)
{
if (Game1.random.NextDouble() < Convert.ToDouble(objectsSplit[i + 1]))
{
objectsToDrop.Add(Convert.ToInt32(objectsSplit[i]));
}
}
resilience.Value = Convert.ToInt32(monsterInfo[7]);
jitteriness.Value = Convert.ToDouble(monsterInfo[8]);
base.willDestroyObjectsUnderfoot = false;
base.moveTowardPlayer(Convert.ToInt32(monsterInfo[9]));
base.speed = Convert.ToInt32(monsterInfo[10]);
missChance.Value = Convert.ToDouble(monsterInfo[11]);
mineMonster.Value = Convert.ToBoolean(monsterInfo[12]);
if (maxTimesReachedMineBottom() >= 1 && mineMonster)
{
resilience.Value += resilience.Value / 2;
missChance.Value *= 2.0;
Health += Game1.random.Next(0, Health);
DamageToFarmer += Game1.random.Next(0, DamageToFarmer / 2);
coinsToDrop.Value += Game1.random.Next(0, coinsToDrop + 1);
if (Game1.random.NextDouble() < 0.001)
{
objectsToDrop.Add((Game1.random.NextDouble() < 0.5) ? 72 : 74);
}
}
try
{
ExperienceGained = Convert.ToInt32(monsterInfo[13]);
}
catch (Exception)
{
ExperienceGained = 1;
}
if (LocalizedContentManager.CurrentLanguageCode != LocalizedContentManager.LanguageCode.en)
{
base.displayName = monsterInfo[monsterInfo.Length - 1];
}
}
19
Source : PhonePatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
internal static void GameLocation_resetLocalState_postfix(GameLocation __instance)
{
if (ModEntry.isReminiscing)
{
if (ModEntry.isReminiscingAtNight)
{
Monitor.Log($"Reminiscing at night");
__instance.LightLevel = 0f;
Game1.globalOutdoorLighting = 1f;
float transparency = Math.Min(0.93f, 0.75f + ((float)(2400 - Game1.getTrulyDarkTime()) + (float)Game1.gameTimeInterval / 7000f * 16.6f) * 0.000625f);
Game1.outdoorLight = Game1.eveningColor * transparency;
if (!(__instance is MineShaft) && !(__instance is Woods))
{
__instance.lightGlows.Clear();
}
PropertyValue nightTiles;
__instance.map.Properties.TryGetValue("NightTiles", out nightTiles);
if (nightTiles != null)
{
string[] split6 = nightTiles.ToString().Split(new char[]
{
' '
});
for (int i3 = 0; i3 < split6.Length; i3 += 4)
{
if ((!split6[i3 + 3].Equals("726") || !Game1.MasterPlayer.mailReceived.Contains("pamHouseUpgrade")) && __instance.map.GetLayer(split6[i3]).Tiles[int.Parse(split6[i3 + 1]), int.Parse(split6[i3 + 2])] != null)
{
__instance.map.GetLayer(split6[i3]).Tiles[int.Parse(split6[i3 + 1]), int.Parse(split6[i3 + 2])].TileIndex = int.Parse(split6[i3 + 3]);
}
}
}
}
else
{
Monitor.Log($"Reminiscing during the day");
return;
__instance.LightLevel = 1f;
Game1.globalOutdoorLighting = 1f;
Game1.outdoorLight = Color.White;
Game1.ambientLight = Color.White;
PropertyValue dayTiles;
__instance.map.Properties.TryGetValue("DayTiles", out dayTiles);
if (dayTiles != null)
{
string[] split5 = dayTiles.ToString().Trim().Split(new char[]
{
' '
});
for (int i2 = 0; i2 < split5.Length; i2 += 4)
{
if ((!split5[i2 + 3].Equals("720") || !Game1.MasterPlayer.mailReceived.Contains("pamHouseUpgrade")) && __instance.map.GetLayer(split5[i2]).Tiles[Convert.ToInt32(split5[i2 + 1]), Convert.ToInt32(split5[i2 + 2])] != null)
{
__instance.map.GetLayer(split5[i2]).Tiles[Convert.ToInt32(split5[i2 + 1]), Convert.ToInt32(split5[i2 + 2])].TileIndex = Convert.ToInt32(split5[i2 + 3]);
}
}
}
}
}
}
19
Source : FamiliarsUtils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void monsterDrop(Familiar familiar, Monster monster, Farmer owner)
{
IList<int> objects = monster.objectsToDrop;
if (Game1.player.isWearingRing(526))
{
string result = "";
Game1.content.Load<Dictionary<string, string>>("Data\\Monsters").TryGetValue(monster.Name, out result);
if (result != null && result.Length > 0)
{
string[] objectsSplit = result.Split(new char[]
{
'/'
})[6].Split(new char[]
{
' '
});
for (int i = 0; i < objectsSplit.Length; i += 2)
{
if (Game1.random.NextDouble() < Convert.ToDouble(objectsSplit[i + 1]))
{
objects.Add(Convert.ToInt32(objectsSplit[i]));
}
}
}
}
if (objects == null || objects.Count == 0)
return;
int objectToAdd = objects[Game1.random.Next(objects.Count)];
if (objectToAdd < 0)
{
familiar.currentLocation.debris.Add(Game1.createItemDebris(new StardewValley.Object(Math.Abs(objectToAdd), Game1.random.Next(1, 4)), familiar.position, Game1.random.Next(4)));
}
else
{
familiar.currentLocation.debris.Add(Game1.createItemDebris(new StardewValley.Object(Math.Abs(objectToAdd), 1), familiar.position, Game1.random.Next(4)));
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void Utility_isThereAFarmerOrCharacterWithinDistance_postfix(ref Character __result, Vector2 tileLocation, int tilesAway, GameLocation environment)
{
if (!Config.Enabled || __result == null || !(__result is NPC) || __result is Horse || !(environment is Town) || !Config.SpecificCharacters.ContainsKey(__result.name))
{
return;
}
string s = environment.doesTileHaveProperty((int)tileLocation.X, (int)tileLocation.Y, "Action", "Buildings");
int whichCan = (s != null) ? Convert.ToInt32(s.Split(' ')[1]) : -1;
NetArray<bool, NetBool> garbageChecked = PHelper.Reflection.GetField<NetArray<bool, NetBool>>(environment, "garbageChecked").GetValue();
if (whichCan >= 0 && whichCan < garbageChecked.Length)
{
PMonitor.Log($"trash voyer");
Reactor r = Config.SpecificCharacters[__result.name];
__result.doEmote(r.emote, true);
(__result as NPC).setNewDialogue(Game1.content.LoadString(r.dialogue), true, true);
Game1.player.changeFriendship(r.points, __result as NPC);
Game1.drawDialogue(__result as NPC);
__result = null;
}
}
19
Source : TitanSkinPreset.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public override void Load()
{
using (AnarchyStorage storage = new AnarchyStorage(FullPath, '`', false))
{
storage.Load();
storage.AutoSave = false;
RandomizePairs = storage.GetBool(nameof(RandomizePairs));
Annie = storage.GetString(nameof(Annie));
Colossal = storage.GetString(nameof(Colossal));
Eren = storage.GetString(nameof(Eren));
Bodies = storage.GetString(nameof(Bodies)).Split(',');
Eyes = storage.GetString(nameof(Eyes)).Split(',');
Hairs = storage.GetString(nameof(Hairs)).Split(',');
string[] tmp = storage.GetString(nameof(HairTypes), "-1,-1,-1,-1,-1").Split(',');
HairTypes = new HairType[Length].Select(x => HairType.Random).ToArray();
for (int i = 0; i < tmp.Length; i++)
{
HairTypes[i] = (HairType)Convert.ToInt32(tmp[i]);
}
}
}
19
Source : LoadScreen.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private IEnumerator Load()
{
string profile = "";
Info.text = "Loading configuration...";
using (ConfigFile file = new ConfigFile(Application.dataPath + "/Configuration/Settings.ini", ' ', false))
{
file.Load();
file.AutoSave = false;
string[] res = file.GetString("resolution").Split('x');
int width = Convert.ToInt32(res[0]);
int height = Convert.ToInt32(res[1]);
Screen.SetResolution(width, height, file.GetBool("fullscreen"));
profile = file.GetString("profile");
int fps = file.GetInt("fps");
Application.targetFrameRate = fps >= 30 ? fps : -1;
QualitySettings.SetQualityLevel(file.GetInt("graphics"), true);
Localization.Language.SetLanguage(file.GetString("language"));
Configuration.Settings.Load();
Configuration.VideoSettings.Apply();
}
yield return new WaitForSeconds(0.5f);
Info.text = "Loading RCreplacedets...";
yield return StartCoroutine(RC.RCManager.Downloadreplacedets());
Optimization.Caching.Pool.Create();
yield return new WaitForSeconds(0.5f);
Info.text = $"Loading profile({profile})..";
User.LoadProfile(profile);
Localization.Language.UpdateFormats();
Localization.Locale loc = new Localization.Locale("GUI", true);
GUI.LabelEnabled = loc["enabled"];
GUI.LabelDisabled = loc["disabled"];
yield return new WaitForSeconds(0.5f);
Info.text = "Loading visuals..";
Style.Load();
Style.ResetScreenParameters();
UIManager.UpdateGUIScaling();
Optimization.Labels.Font = Style.Font;
yield return new WaitForSeconds(0.5f);
Info.text = "Enjoy!";
Optimization.Labels.VERSION = string.Format(UIMainReferences.VersionShow, AnarchyManager.AnarchyVersion.ToString());
textUpdate = false;
Loading.text = "Loading complete";
yield return new WaitForSeconds(2f);
Destroy(gameObject);
AnarchyManager.Background.Enable();
}
19
Source : LoadScreen.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private IEnumerator Load()
{
string profile = "";
Info.text = "Loading configuration...";
using (ConfigFile file = new ConfigFile(Application.dataPath + "/Configuration/Settings.ini", ' ', false))
{
file.Load();
file.AutoSave = false;
string[] res = file.GetString("resolution").Split('x');
Screen.SetResolution(Convert.ToInt32(res[0]), Convert.ToInt32(res[1]), file.GetBool("fullscreen"));
profile = file.GetString("profile");
int fps = file.GetInt("fps");
Application.targetFrameRate = fps >= 30 ? fps : -1;
Time.fixedDeltaTime = (float)Math.Round(1f / file.GetInt("fixedUpdateCount"), 8);
PhotonNetwork.sendRate = file.GetInt("fixedUpdateCount");
QualitySettings.SetQualityLevel(file.GetInt("graphics"), true);
Localization.Language.SetLanguage(file.GetString("language"));
Configuration.Settings.Load();
}
yield return new WaitForSeconds(0.5f);
Info.text = "Loading RCreplacedets...";
yield return StartCoroutine(RC.RCManager.Downloadreplacedets());
Optimization.Caching.Pool.Create();
yield return new WaitForSeconds(0.5f);
Info.text = $"Loading profile({profile})..";
User.LoadProfile(profile);
Localization.Language.UpdateFormats();
Localization.Locale loc = new Localization.Locale("GUI", true);
GUI.LabelEnabled = loc["enabled"];
GUI.LabelDisabled = loc["disabled"];
yield return new WaitForSeconds(0.5f);
Info.text = "Loading visuals..";
Style.Load();
UIManager.UpdateGUIScaling();
Optimization.Labels.Font = Style.Font;
yield return new WaitForSeconds(0.5f);
Info.text = "Enjoy!";
Optimization.Labels.VERSION = UIMainReferences.VersionShow;
textUpdate = false;
Loading.text = "Loading complete";
yield return new WaitForSeconds(2f);
Destroy(gameObject);
AnarchyManager.Background.Enable();
}
19
Source : Style.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private static void TryApplyPublicSettings()
{
FontName = PublicSettings[0];
BackgroundHex = PublicSettings[1];
BackgroundTransparency = System.Convert.ToInt32(PublicSettings[2]);
UseVectors = System.Convert.ToBoolean(PublicSettings[9]);
int j = 0;
for (int i = 3; i < 9; i++)
{
TextColors[j++] = PublicSettings[i];
}
j = 0;
for (int i = 10; i < 16; i++)
{
TextureDeltas[j++] = PublicSettings[i].ParseVector3();
}
j = 0;
for (int i = 16; i < 22; i++)
{
TextureColors[j++] = PublicSettings[i].HexToColor();
}
}
19
Source : Style.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static void Load()
{
using (ConfigFile config = new ConfigFile(Application.dataPath + "/Configuration/Visuals.ini", ':', false))
{
using (ConfigFile settings = new ConfigFile(Application.dataPath + "/Configuration/Settings.ini", ' ', false))
{
settings.Load();
settings.AutoSave = true;
string[] res = settings.GetString("resolution").Split('x');
ScreenWidthDefault = (float)System.Convert.ToInt32(res[0]);
ScreenHeightDefault = (float)System.Convert.ToInt32(res[1]);
if (PlayerPrefs.GetInt("AnarchyModLaunched") == 0)
{
PlayerPrefs.SetInt("AnarchyModLaunched", 1);
float xScale = ScreenWidthDefault / 1920f;
float yScale = ScreenHeightDefault / 1080f;
float totalScale = (xScale + yScale) / 2f;
UIManager.HUDScaleGUI.Value = Mathf.Clamp(totalScale, 0.75f, 1.5f);
UIManager.HUDScaleGUI.Save();
}
ResetScreenParameters();
}
config.Load();
config.AutoSave = false;
FontName = config.GetString("font");
Font = Anarchyreplacedets.Load<Font>(FontName);
BackgroundHex = config.GetString("background");
BackgroundTransparency = config.GetInt("backgroundTransparency");
TextColors = new string[6];
TextColors[0] = config.GetString("textNormal");
TextColors[1] = config.GetString("textHover");
TextColors[2] = config.GetString("textActive");
TextColors[3] = config.GetString("textOnNormal");
TextColors[4] = config.GetString("textOnHover");
TextColors[5] = config.GetString("textOnActive");
TextureDeltas = new Vector3[6];
TextureDeltas[0] = config.GetString("normalVector").ParseVector3();
TextureDeltas[1] = config.GetString("hoverVector").ParseVector3();
TextureDeltas[2] = config.GetString("activeVector").ParseVector3();
TextureDeltas[3] = config.GetString("onNormalVector").ParseVector3();
TextureDeltas[4] = config.GetString("onHoverVector").ParseVector3();
TextureDeltas[5] = config.GetString("onActiveVector").ParseVector3();
if (!config.AllValues.ContainsKey("useVectors"))
{
UseVectors = false;
}
else
{
UseVectors = config.GetBool("useVectors");
}
TextureColors = new Color[6];
if (!config.AllValues.ContainsKey("colorNormal") || !config.AllValues.ContainsKey("colorHover") || !config.AllValues.ContainsKey("colorActive") ||
!config.AllValues.ContainsKey("colorOnNormal") || !config.AllValues.ContainsKey("colorOnHover") || !config.AllValues.ContainsKey("colorOnActive"))
{
UseVectors = true;
Color[] colors = Helper.TextureColors(BackgroundColor, 6);
for (int i = 0; i < 6; i++)
{
TextureColors[i] = colors[i];
}
UseVectors = false;
}
else
{
TextureColors[0] = config.GetString("colorNormal").HexToColor();
TextureColors[1] = config.GetString("colorHover").HexToColor();
TextureColors[2] = config.GetString("colorActive").HexToColor();
TextureColors[3] = config.GetString("colorOnNormal").HexToColor();
TextureColors[4] = config.GetString("colorOnHover").HexToColor();
TextureColors[5] = config.GetString("colorOnActive").HexToColor();
}
LoadPublicSettings();
}
wasLoaded = true;
Initialize();
}
19
Source : Plant.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public bool RequirementsMet(MapTile map, Point position)
{
if (requirement.Equals(""))
return true;
if (requirement.Contains("tile_nearby;")) {
if (requirement.Contains("water;"))
{
int dist = System.Convert.ToInt32(requirement.Replace("tile_nearby;water;", ""));
if (map.GetClosestOfTileTypeToPos(position, new Water()).DistFrom(position) < dist)
return true;
}
}
if (requirement.Contains("block_nearby;")) {
if (requirement.Contains("wall;")) {
int dist = System.Convert.ToInt32(requirement.Replace("block_nearby;wall;", ""));
if (map.GetClosestOfBlockTypeToPos(position, BlockType.Wall).DistFrom(position) < dist)
return true;
}
else if (requirement.Contains("tree;")) {
int dist = System.Convert.ToInt32(requirement.Replace("block_nearby;tree;", ""));
if (map.GetClosestOfBlockTypeToPos(position, BlockType.Tree).DistFrom(position) < dist)
return true;
}
}
return false;
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Dungeon GetNextDungeon(int preferredLvl)
{
Dungeon dungeon = null;
XElement dungeonData = null;
// load all the dungeons
XElement root = XElement.Load("res/data/DungeonTypes.xml");
IEnumerable<XElement> dungeons =
from el in root.Elements("dungeon")
select el;
// get the correct dungeon based on lvl (need to expand this to accomodate multiple dungeons)
foreach (XElement dun in dungeons) {
int minLvl;
int maxLvl;
XElement lvl_range = dun.Element("level_range");
minLvl = System.Convert.ToInt32(ReadAttribute(lvl_range.Attribute("min_lvl")));
maxLvl = System.Convert.ToInt32(ReadAttribute(lvl_range.Attribute("max_lvl")));
if (preferredLvl >= minLvl && preferredLvl <= maxLvl) {
dungeonData = dun;
break;
}
}
// convert the dungeon's data into a clreplaced
string name = "";
int floors;
List<string> monsters = new List<string>();
List<string> names = new List<string>();
foreach (XElement el in dungeonData.Element("names").Elements("name"))
names.Add(ReadElement(el));
name = names[Program.RNG.Next(0, names.Count)];
Enum.TryParse(ReadAttribute(dungeonData.Element("algorithms").Element("algorithm").Attribute("name")), out DungeonType dungeonType);
floors = System.Convert.ToInt32(ReadAttribute(dungeonData.Element("floors").FirstAttribute));
// get the monsters
// get permanent monster types
string monsterNames = ReadAttribute(dungeonData.Element("monster_types").Attribute("persistent"));
int i = 0;
monsters.Add("");
foreach (char c in monsterNames) {
if (c == ' ') { i++; monsters.Add(""); }
else
monsters[i] = monsters[i] + c;
}
// pick random unique monster types
List<string> uniqueMonsters = new List<string>();
int uniqueCount = System.Convert.ToInt32(ReadAttribute(dungeonData.Element("monster_types").Attribute("unique_count")));
monsterNames = ReadAttribute(dungeonData.Element("monster_types").Attribute("unique"));
i = 0;
uniqueMonsters.Add("");
foreach (char c in monsterNames) {
if (c == ' ') { i++; uniqueMonsters.Add(""); }
else
uniqueMonsters[i] = uniqueMonsters[i] + c;
}
int max = monsters.Count + uniqueCount;
while (monsters.Count < max) {
int rand = Program.RNG.Next(0, uniqueMonsters.Count);
monsters.Add(uniqueMonsters[rand]);
uniqueMonsters.RemoveAt(rand);
}
dungeon = new Dungeon(name, dungeonType, monsters, floors);
return dungeon;
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Monster GetMonster(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
{
XElement monsterData = null;
// load all the effects
XElement root = XElement.Load( "res/data/MonsterTypes.xml" );
IEnumerable<XElement> monsters =
from el in root.Elements( "monster" )
select el;
// choose the right effect
foreach ( XElement m in monsters )
if ( ReadAttribute( m.FirstAttribute ) == name )
monsterData = m;
if ( monsterData == null )
return null;
byte graphic = System.Convert.ToByte( ReadAttribute( monsterData.Attribute( "ascii_char" ) ) );
string faction = System.Convert.ToString( ReadAttribute( monsterData.Attribute( "faction" ) ) );
int sightDist = System.Convert.ToInt32( ReadAttribute( monsterData.Attribute( "sight_dist" ) ) );
byte r = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "r" ) ) ),
g = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "g" ) ) ),
b = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "b" ) ) );
Color? color = new Color( r, g, b );
Enum.TryParse(ReadElement(monsterData.Element("diet")), out DietType diet);
IEnumerable<XElement> majorAttData = from el in monsterData.Element( "clreplaced" ).Element( "major_attributes" ).Elements( "attribute" )
select el;
List<Attribute> majorAtt = new List<Attribute>();
foreach (XElement attE in majorAttData) {
Enum.TryParse( ReadElement( attE ), out Attribute att );
majorAtt.Add( att );
} // translate IEnumerable to List
IEnumerable<XElement> majorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "major_skills" ).Elements( "skill" )
select el;
List<Skill> majorSkills = new List<Skill>();
foreach ( XElement skillE in majorSkillsData ) {
Enum.TryParse( ReadElement( skillE ), out Skill skill );
majorSkills.Add( skill );
} // translate IEnumerable to List
IEnumerable<XElement> minorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "minor_skills" ).Elements( "skill" )
select el;
List<Skill> minorSkills = new List<Skill>();
foreach (XElement skillE in minorSkillsData) {
Enum.TryParse( ReadElement( skillE ), out Skill skill );
minorSkills.Add( skill );
} // translate IEnumerable to List
Clreplaced uClreplaced = new Clreplaced( majorAtt, majorSkills, minorSkills );
IEnumerable<XElement> baseDesiresData = from el in monsterData.Element( "base_desires" ).Elements( "desire_type" )
select el;
Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
foreach (XElement desireTypeE in baseDesiresData) {
Enum.TryParse( ReadAttribute( desireTypeE.FirstAttribute ), out DesireType desireType );
baseDesires.Add( desireType, System.Convert.ToInt32( ReadAttribute( desireTypeE.LastAttribute ) ) );
} // translate IEnumerable to List
return new Monster( map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic );
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Animal GetAnimal(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
{
XElement creatureData = null;
// load all the creatures
XElement root = XElement.Load("res/data/OverworldCreatureTypes.xml");
IEnumerable<XElement> creatures =
from el in root.Elements("creature")
select el;
// choose the right creature
foreach (XElement c in creatures)
if (ReadAttribute(c.FirstAttribute).Equals(name))
creatureData = c;
if (creatureData == null)
return null;
byte graphic = System.Convert.ToByte(ReadAttribute(creatureData.Attribute("ascii_char")));
string faction = System.Convert.ToString(ReadAttribute(creatureData.Attribute("faction")));
int sightDist = System.Convert.ToInt32(ReadAttribute(creatureData.Attribute("sight_dist")));
byte r = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("r"))),
g = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("g"))),
b = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("b")));
Color? color = new Color(r, g, b);
Enum.TryParse(ReadElement(creatureData.Element("diet")), out DietType diet);
IEnumerable<XElement> majorAttData = from el in creatureData.Element("clreplaced").Element("major_attributes").Elements("attribute")
select el;
List<Attribute> majorAtt = new List<Attribute>();
foreach (XElement attE in majorAttData) {
Enum.TryParse(ReadElement(attE), out Attribute att);
majorAtt.Add(att);
}
IEnumerable<XElement> majorSkillsData = from el in creatureData.Element("clreplaced").Element("major_skills").Elements("skill")
select el;
List<Skill> majorSkills = new List<Skill>();
foreach (XElement skillE in majorSkillsData) {
Enum.TryParse(ReadElement(skillE), out Skill skill);
majorSkills.Add(skill);
}
IEnumerable<XElement> minorSkillsData = from el in creatureData.Element("clreplaced").Element("minor_skills").Elements("skill")
select el;
List<Skill> minorSkills = new List<Skill>();
foreach (XElement skillE in minorSkillsData) {
Enum.TryParse(ReadElement(skillE), out Skill skill);
minorSkills.Add(skill);
}
Clreplaced uClreplaced = new Clreplaced(majorAtt, majorSkills, minorSkills);
IEnumerable<XElement> baseDesiresData = from el in creatureData.Element("base_desires").Elements("desire_type")
select el;
Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
foreach (XElement desireTypeE in baseDesiresData) {
Enum.TryParse(ReadAttribute(desireTypeE.FirstAttribute), out DesireType desireType);
baseDesires.Add(desireType, System.Convert.ToInt32(ReadAttribute(desireTypeE.LastAttribute)));
}
return new Animal(map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic);
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Plant GetPlant(string name)
{
XElement plantData = null;
// load all the plants
XElement root = XElement.Load("res/data/PlantTypes.xml");
IEnumerable<XElement> plants =
from el in root.Elements("plant")
select el;
// choose the right creature
foreach (XElement p in plants)
if (ReadAttribute(p.FirstAttribute).Equals(name))
plantData = p;
if (plantData == null)
return null;
bool edible = System.Convert.ToBoolean(ReadAttribute(plantData.Element("edible").Attribute("bool")));
int growthInterval = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("growth_interval")));
int seedRadius = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("seed_radius")));
byte r = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("r"))),
g = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("g"))),
b = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("b")));
Color? foreColor = new Color(r, g, b);
IEnumerable<XElement> growthStagesTemp =
from el in plantData.Element("growth_stages").Elements("growth_stage")
select el;
List<byte> growthStages = new List<byte>();
foreach (XElement growthStage in growthStagesTemp)
growthStages.Add(System.Convert.ToByte(ReadAttribute(growthStage.Attribute("graphic"))));
string requirement;
if (ReadAttribute(plantData.Element("requirement").FirstAttribute).Equals(""))
requirement = "";
else {
requirement =
ReadAttribute(plantData.Element("requirement").FirstAttribute)
+ ';'
+ ReadAttribute(plantData.Element("requirement").Attribute("type"))
+ ';'
+ ReadAttribute(plantData.Element("requirement").Attribute("dist"));
}
return new Plant(growthStages[0], name, growthInterval, seedRadius, growthStages, requirement, edible, foreColor);
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static WeaponEnchantment GetWeaponEnchantment( string enchantName )
{
WeaponEnchantment wEnchant = null;
XElement wEnchantData = null;
// load all the enchantments
XElement root = XElement.Load("res/data/WeaponEnchantTypes.xml");
IEnumerable<XElement> enchants =
from el in root.Elements("enchantment")
select el;
// choose the right enchantment
foreach (XElement e in enchants)
if (ReadAttribute(e.Attribute("name")).Equals(enchantName))
wEnchantData = e;
if (wEnchantData == null)
return null;
string name = enchantName;
List<XElement> partNames = wEnchantData.Element("part_names").Elements().ToList();
string partName = ReadAttribute(partNames[Program.RNG.Next(0, partNames.Count)].FirstAttribute);
Enum.TryParse(ReadAttribute(wEnchantData.Attribute("damage_type")), out DamageType damageType);
Effect appliedEffect = GetEffect(ReadAttribute(wEnchantData.Attribute("applied_effect")));
int victimDamage = Program.RNG.Next(System.Convert.ToInt32(ReadAttribute(wEnchantData.Element("victim_damage").FirstAttribute)), System.Convert.ToInt32(ReadAttribute(wEnchantData.Element("victim_damage").LastAttribute)));
wEnchant = new WeaponEnchantment(name, partName, damageType, victimDamage, appliedEffect);
return wEnchant;
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Effect GetEffect( string effectName )
{
Effect effect = null;
XElement effectData = null;
// load all the effects
XElement root = XElement.Load("res/data/EffectTypes.xml");
IEnumerable<XElement> effects =
from el in root.Elements("effect")
select el;
// choose the right effect
foreach (XElement e in effects)
if (ReadAttribute(e.FirstAttribute) == effectName)
effectData = e;
if (effectData == null)
return null;
// load the victim damage parameters
int victimDmgMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_damage").FirstAttribute)),
victimDmgMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_damage").LastAttribute)),
victimMagickaDrainMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_drain").FirstAttribute)),
victimMagickaDrainMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_drain").LastAttribute)),
victimStaminaDrainMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_drain").FirstAttribute)),
victimStaminaDrainMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_drain").LastAttribute));
int[] victimResourceDamage = new int[3];
victimResourceDamage[0] = Program.RNG.Next(victimDmgMin, victimDmgMax + 1);
victimResourceDamage[1] = Program.RNG.Next(victimMagickaDrainMin, victimMagickaDrainMax + 1);
victimResourceDamage[2] = Program.RNG.Next(victimStaminaDrainMin, victimStaminaDrainMax + 1);
int victimHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_healing").FirstAttribute)),
victimHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_healing").LastAttribute)),
victimMagickaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_healing").FirstAttribute)),
victimMagickaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_healing").LastAttribute)),
victimStaminaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_healing").FirstAttribute)),
victimStaminaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_healing").LastAttribute));
int[] victimResourceHealing = new int[3];
victimResourceHealing[0] = Program.RNG.Next(victimHealingMin, victimHealingMax + 1);
victimResourceHealing[1] = Program.RNG.Next(victimMagickaHealingMin, victimMagickaHealingMax + 1);
victimResourceHealing[2] = Program.RNG.Next(victimStaminaHealingMin, victimStaminaHealingMax + 1);
int userHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_healing").FirstAttribute)),
userHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_healing").LastAttribute)),
userMagickaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_magicka_healing").FirstAttribute)),
userMagickaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_magicka_healing").LastAttribute)),
userStaminaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_stamina_healing").FirstAttribute)),
userStaminaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_stamina_healing").LastAttribute));
int[] userResourceHealing = new int[3];
userResourceHealing[0] = Program.RNG.Next(userHealingMin, userHealingMax + 1);
userResourceHealing[1] = Program.RNG.Next(userMagickaHealingMin, userMagickaHealingMax + 1);
userResourceHealing[2] = Program.RNG.Next(userStaminaHealingMin, userStaminaHealingMax + 1);
// load the damage type
Enum.TryParse(ReadElement(effectData.Element("victim_damage_type")), out DamageType victimDamageType);
// load the status effect
Enum.TryParse(ReadAttribute(effectData.Element("victim_status_effect").FirstAttribute), out StatusEffect statusEffect);
// load the victim healing parameters
// load the user healing parameters
int turnsMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("turns").FirstAttribute)),
turnsMax = victimDmgMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("turns").LastAttribute));
int chance = System.Convert.ToInt32(ReadAttribute(effectData.Element("inflict_chance").FirstAttribute));
int turns = Program.RNG.Next(turnsMin, turnsMax + 1);
effect = new Effect(effectName, victimResourceDamage, victimDamageType, statusEffect, victimResourceHealing, userResourceHealing, chance, turns);
return effect;
}
19
Source : PreferencesDialog.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
public void LoadPreferences()
{
string val;
//
val = prefs["Undo.Limited"];
try {
bool limited = Convert.ToBoolean(val);
UndoLimitedRadioButton.Active = limited;
UndoUnlimitedRadioButton.Active = !limited;
}
catch (FormatException e) {
System.Console.WriteLine(e.Message);
UndoLimitedRadioButton.Active = true;
}
//
val = prefs["Undo.Actions"];
try {
int actions = Convert.ToInt32(val);
UndoActionsSpinButton.Value = actions;
}
catch (FormatException e) {
System.Console.WriteLine(e.Message);
UndoActionsSpinButton.Value = 100;
}
//
val = prefs["Undo.KeepAfterSave"];
KeepUndoAlwaysRadioButton.Active = false;
KeepUndoMemoryRadioButton.Active = false;
KeepUndoNeverRadioButton.Active = false;
switch(val.ToLower()) {
case "always":
KeepUndoAlwaysRadioButton.Active = true;
break;
case "never":
KeepUndoNeverRadioButton.Active = true;
break;
case "memory":
default:
KeepUndoMemoryRadioButton.Active = true;
break;
}
}
See More Examples