System.DateTime.ToString()

Here are the examples of the csharp api System.DateTime.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1439 Examples 7

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

public static SearchAndIndexQueryResult FetchBasliksUsingSearch(bool fresh, string content, string suser, DateTime begin, DateTime end, int pageNumber, string pagerHash, bool leaveDatesAsIs)
        {
            SearchAndIndexQueryResult resultSet;
            SqlServerIo sql;
            TimeSpan invTimeout;
            int rowBegin, rowEnd;
            string query;
            KeysetId keysetId;
            string baslik, descr, deceptedDate;
            int entryCount;
            bool resultCached;

            rowBegin = (pageNumber * BasliksPerPage) + 1;
            rowEnd = rowBegin + BasliksPerPage - 1;

            //Workarounds, workarounds, workarounds !
            if (begin != DateTime.MinValue && end != DateTime.MinValue)
            {
                if (leaveDatesAsIs)
                {
                    deceptedDate = begin.AddTicks((end - begin).Ticks / 2).ToString();
                }
                else
                {
                    //push it out of from the search date range to reverse daterange check logic
                    deceptedDate = end.AddDays(2).ToString();
                }
            }
            else
                deceptedDate = string.Empty;

            query = BuildFetchSQLQuery(ref pagerHash, content, suser, begin, end, rowBegin, rowEnd);


            if (fresh)
            {
                keysetId = KeysetId.Todays(true);
                invTimeout = TodaysTimeout;
            }
            else
            {
                keysetId = KeysetId.Search(pagerHash,true);
                invTimeout = SearchResultTimeout;
            }

            resultCached = CacheManager.TryGetCachedQueryResult<SearchAndIndexQueryResult>(query, out resultSet);

            if (!resultCached)
            {
                sql = SqlServerIo.Create();

                if (!sql.Execute(false, query))
                {
                    SqlServerIo.Release(sql);
                    return new SearchAndIndexQueryResult();
                }

                resultSet = new SearchAndIndexQueryResult
                {
                    PagerHash = pagerHash
                };

                while (sql.Read())
                {
                    baslik = sql.GetValueOfColumn<string>("Baslik");
                    entryCount = sql.GetValueOfColumn<int>("EntryCount");

                    if (resultSet.TotalRecordCount == 0)
                        resultSet.TotalRecordCount = sql.GetValueOfColumn<int>("TotalRecordCount");

                    if (entryCount>0)
                        descr = content;
                    else
                        descr = Strev(content);

                    if (string.IsNullOrEmpty(suser))
                        suser = string.Empty;

                    resultSet.Entries.Add(
                        new Entry(
                            baslik, 
                            suser, 
                            deceptedDate, 
                            descr,entryCount)
                            );

                    resultSet.PhysicalRecordCount++;
                }

                resultSet.LogicalRecordCount = resultSet.Entries.Count;

                SqlServerIo.Release(sql);

                CacheManager.CacheObject(keysetId,true, query, resultSet,invTimeout);
            }

            return resultSet;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

19 Source : CSRedisClientListTests.cs
with MIT License
from 2881099

[Fact]
		public void LSet() {
			replacedert.Equal(8, rds.RPush("TestLSet", base.Clreplaced, base.Clreplaced, base.Bytes, base.Bytes, base.String, base.String, base.Null, base.Null));

			var now = DateTime.Now;
			replacedert.True(rds.LSet("TestLSet", -1, now));
			replacedert.Equal(now.ToString(), rds.LIndex<DateTime>("TestLSet", -1).ToString());
		}

19 Source : Program.cs
with Apache License 2.0
from 214175590

static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】:" + ex.GetType().Name);
                sb.AppendLine("【异常信息】:" + ex.Message);
                sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】:" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

19 Source : ListsTests.cs
with MIT License
from 2881099

[Fact]
        public void LSet()
        {
            cli.Del("TestLSet");
            replacedert.Equal(8, cli.RPush("TestLSet", Clreplaced, Clreplaced, Bytes, Bytes, String, String, Null, Null));

            var now = DateTime.Now;
            cli.LSet("TestLSet", -1, now);
            replacedert.Equal(now.ToString(), cli.LIndex<DateTime>("TestLSet", -1).ToString());
        }

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust

private int V2rayStartNew(string configStr)
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return -1;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        Arguments = "-config stdin:",
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.BeginOutputReadLine();

                p.StandardInput.Write(configStr);
                p.StandardInput.Close();

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
                return p.Id;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(false, msg);
                return -1;
            }
        }

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust

private void V2rayStart()
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.PriorityClreplaced = ProcessPriorityClreplaced.High;
                p.BeginOutputReadLine();
                //processId = p.Id;
                _process = p;

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(true, msg);
            }
        }

19 Source : SocketServiceImpl.cs
with MIT License
from 499116344

public void MessageLog(string content)
        {
            Console.WriteLine($"{DateTime.Now.ToString()}--{content}");
        }

19 Source : QQUser.cs
with MIT License
from 499116344

public void MessageLog(string str)
        {
            Console.WriteLine($"{DateTime.Now.ToString()}--{str}");
        }

19 Source : ConfigDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

private List<ConfigModel> GetAppConfigValue(Dictionary<string,string> configDic, Type type, string parentName = "")
        {
            var configs = new List<ConfigModel>();
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {

                string name = prop.Name;
                string key = string.IsNullOrEmpty(parentName) ? $"{name}" : $"{parentName}:{name}";

                if (prop.PropertyType.IsValueType || prop.PropertyType.Name.StartsWith("String"))
                {
                    string value = "";
                    try
                    {
                        configDic.TryGetValue(key, out  value);
                    }
                    catch (Exception)
                    {

                    }

                    if (string.IsNullOrEmpty(value))
                    {
                        if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?) ||
                            prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?) ||
                            prop.PropertyType == typeof(float) || prop.PropertyType == typeof(float?) ||
                            prop.PropertyType == typeof(double)|| prop.PropertyType == typeof(double?) 
                            )
                        {
                            var defaultValue = Activator.CreateInstance(prop.PropertyType);
                            value = defaultValue.ToString();
                        }
                        else if (prop.PropertyType == typeof(DateTime?) || prop.PropertyType == typeof(DateTime))
                        {
                            value = DateTime.Now.ToString();
                        }
                        else if (prop.PropertyType == typeof(Guid?) || prop.PropertyType == typeof(Guid))
                        {
                            value = Guid.Empty.ToString();
                        }
                    }

                    var attribute = prop.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
                    configs.Add(new ConfigModel
                    {
                        Key = key,
                        Name = attribute?.DisplayName ?? name,
                        Value = value,
                        Type = prop.PropertyType
                    });
                }
                else
                {
                    configs.AddRange(GetAppConfigValue(configDic, prop.PropertyType, key));
                }

            }

            return configs;
        }

19 Source : FlightPlan.cs
with MIT License
from 8bitbytes

public void Save(string path)
        {
            if (Name == null)
            {
                Name = $"FP_{System.DateTime.Now.ToString().Replace("/","-").Replace(":","")}_{System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8)}";
            }
            var contents = JsonConvert.SerializeObject(this);
            var dir = $@"{System.IO.Directory.GetCurrentDirectory()}\{this.Name}.json.fp";
            System.IO.File.WriteAllText(dir, contents);
        }

19 Source : FrmMain.cs
with MIT License
from A-Tabeshfard

private void MnuEditTimeDate_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime DT = DateTime.Now;
                ((FrmContent)ActiveMdiChild).textBox.Text += " " + DT.ToString();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin

public void InitializeCommunicator()
    {
        Application.logMessageReceived += HandleLog;
        logPath = Path.GetFullPath(".") + "/unity-environment.log";
        logWriter = new StreamWriter(logPath, false);
        logWriter.WriteLine(System.DateTime.Now.ToString());
        logWriter.WriteLine(" ");
        logWriter.Close();
        messageHolder = new byte[messageLength];

        // Create a TCP/IP  socket.  
        sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sender.Connect("localhost", comPort);

        AcademyParameters accParamerters = new AcademyParameters();
        accParamerters.brainParameters = new List<BrainParameters>();
        accParamerters.brainNames = new List<string>();
        accParamerters.externalBrainNames = new List<string>();
        accParamerters.apiNumber = api;
        accParamerters.logPath = logPath;
        foreach (Brain b in brains)
        {
            accParamerters.brainParameters.Add(b.brainParameters);
            accParamerters.brainNames.Add(b.gameObject.name);
            if (b.brainType == BrainType.External)
            {
                accParamerters.externalBrainNames.Add(b.gameObject.name);
            }
        }
        accParamerters.AcademyName = academy.gameObject.name;
        accParamerters.resetParameters = academy.resetParameters;

        SendParameters(accParamerters);
    }

19 Source : DevReloadMiddleware.cs
with GNU General Public License v3.0
from abiosoft

private void OnChanged(object source, FileSystemEventArgs e)
        {
            // return if it's an ignored directory
            foreach (string ignoredDirectory in _options.IgnoredSubDirectories)
            {
                var sep = Path.DirectorySeparatorChar;
                if (e.FullPath.Contains($"{sep}{ignoredDirectory}{sep}")) return;
            }

            FileInfo fileInfo = new FileInfo(e.FullPath);
            if (_options.StaticFileExtensions.Length > 0)
            {
                foreach (string extension in _options.StaticFileExtensions)
                {
                    if (fileInfo.Extension.Equals($".{extension.TrimStart('.')}"))
                    {
                        _time = System.DateTime.Now.ToString();
                        break;
                    }
                }
            }
            else
            {
                _time = System.DateTime.Now.ToString();
            }
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
        }

19 Source : PostFSRepo.cs
with Apache License 2.0
from acblog

public PostMetadata GetDefaultMetadata(string id)
        {
            string path = GetPath(id);
            PostMetadata metadata = new PostMetadata
            {
                id = id,
                creationTime = System.IO.File.GetCreationTime(path).ToString(),
                modificationTime = System.IO.File.GetLastWriteTime(path).ToString()
            };
            {
                var relpath = Path.GetDirectoryName(id)?.Replace("\\", "/");
                var items = relpath?.Split("/", StringSplitOptions.RemoveEmptyEntries);
                metadata.category = items ?? Array.Empty<string>();
            }
            return metadata;
        }

19 Source : LayoutFSRepo.cs
with Apache License 2.0
from acblog

protected override Task<Layout> CreateExistedItem(string id, LayoutMetadata metadata, string content)
        {
            string path = GetPath(id);
            if (string.IsNullOrEmpty(metadata.id))
                metadata.id = id;
            if (string.IsNullOrEmpty(metadata.creationTime))
            {
                metadata.creationTime = System.IO.File.GetCreationTime(path).ToString();
            }
            if (string.IsNullOrEmpty(metadata.modificationTime))
            {
                metadata.modificationTime = System.IO.File.GetLastWriteTime(path).ToString();
            }

            var result = metadata.ApplyTo(new Layout());
            result = result with { Template = content };

            return Task.FromResult(result);
        }

19 Source : PageFSRepo.cs
with Apache License 2.0
from acblog

protected override Task<Page> CreateExistedItem(string id, PageMetadata metadata, string content)
        {
            string path = GetPath(id);
            if (string.IsNullOrEmpty(metadata.id))
                metadata.id = id;
            if (string.IsNullOrEmpty(metadata.creationTime))
            {
                metadata.creationTime = System.IO.File.GetCreationTime(path).ToString();
            }
            if (string.IsNullOrEmpty(metadata.modificationTime))
            {
                metadata.modificationTime = System.IO.File.GetLastWriteTime(path).ToString();
            }

            var result = metadata.ApplyTo(new Page());
            result = result with { Content = content };

            return Task.FromResult(result);
        }

19 Source : MainControl.xaml.cs
with MIT License
from Actipro

private void OnScreenTipOpening(object sender, RoutedEventArgs e) {
			// Dynamically generate the screen tip description here
			RibbonControls.Button button = (RibbonControls.Button)sender;
			button.ScreenTipDescription = "This description was generated dynamically at " + DateTime.Now.ToString() + ".";
		}

19 Source : MainControl.xaml.cs
with MIT License
from Actipro

private void OnEditorDoreplacedentTextChanging(object sender, EditorSnapshotChangingEventArgs e) {
			e.Cancel = (cancelCheckBox.IsChecked == true);

			if (e.Cancel) {
				if (alternateTextCheckBox.IsChecked == true) {
					// Temporarily turn off cancel and insert date/time instead
					cancelCheckBox.IsChecked = false;
					editor.ActiveView.ReplaceSelectedText(TextChangeTypes.Custom, DateTime.Now.ToString());
					cancelCheckBox.IsChecked = true;
					MessageBox.Show("Text change cancelled, current date/time inserted instead.", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
				}
				else {
					// Simple cancel
					MessageBox.Show("Text change cancelled.", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
				}
			}
		}

19 Source : ConnectedInstruction_BACKUP_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static void WritetoCsvu(IList<IList<double>> gridValues, string path)
        {
            Console.WriteLine("Write Begin " + DateTime.Now.ToString());
            var sw = new StreamWriter(path);
            var cnt = 0;
            foreach (var row in gridValues)
            {
                sw.WriteLine(row[0] + "," + row[1] + "," + row[2] + "," + row[3] + "," + row[4] + "," + row[5] + "," + row[6]);
                cnt++;
            }
            sw.Close();
            Console.WriteLine("Write Complete " + DateTime.Now.ToString());
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1]+@")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 Source : TrelloDemoCard.cs
with MIT License
from AdamCarballo

private IEnumerator DemoSendCard_Internal() {

        TrelloCard card = new TrelloCard();

        card.name = replacedle.text;
        card.due = DateTime.Today.ToString();
        card.desc = "#" + "Demo " + Application.version + "\n" +
            "___\n" +
            "###System Information\n" +
            "- " + SystemInfo.operatingSystem + "\n" +
            "- " + SystemInfo.processorType + "\n" +
            "- " + SystemInfo.systemMemorySize + " MB\n" +
            "- " + SystemInfo.graphicsDeviceName + " (" + SystemInfo.graphicsDeviceType + ")\n" +
            "\n" +
            "___\n" +
            "###User Description\n" +
            "```\n" +
            desc.text + "\n" +
            "```\n" +
            "___\n" +
            "###Other Information\n" +
            "Playtime: " + String.Format("{0:0}:{1:00}", Mathf.Floor(Time.time / 60), Time.time % 60) + "h" + "\n" +
            "Tracked object position: " + trackedObject.position;

        if (screenshot.isOn) {
            StartCoroutine(UploadJPG());
            while (file == null) {
                yield return null;
            }
            card.fileSource = file;
            card.fileName = DateTime.UtcNow.ToString() + ".jpg";
        }

        trelloSend.SendNewCard(card);
    }

19 Source : IDirectory.cs
with MIT License
from Adoxio

protected static string FormatDateTime(DateTime? dateTime)
		{
			return dateTime == null ? null : dateTime.ToString();
		}

19 Source : DateTimeLiteral.cs
with MIT License
from Adoxio

protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			if (Value == null)
			{
				base.Render(writer);
				return;
			}

			DateTime dt;

			if (Value is DateTime)
			{
				dt = (DateTime)Value;
			}
			else if (Value is DateTime?)
			{
				dt = ((DateTime?)Value).Value;
			}
			else
			{
				dt = DateTime.Parse(Value.ToString());
			}

			if (dt.Kind == DateTimeKind.Utc)
			{
				// check if we are to use the default site timezone
				if (UseSiteTimeZone)
				{
					var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
					var tz = portal.GetTimeZone();
					dt = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

					// if no timezone label provided, use the display name of the current timezone
					if (string.IsNullOrEmpty(TimeZoneLabel))
					{
						TimeZoneLabel = tz.DisplayName;
					}
				}
				else if (!string.IsNullOrEmpty(TimeZone))  // a specific timezone is given
				{
					var tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZone);
					dt = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

					// if no timezone label provided, use the display name of the current timezone
					if (string.IsNullOrEmpty(TimeZoneLabel))
					{	
						TimeZoneLabel = tz.DisplayName;
					}
				}
			}
			
			// output the datetime in the correct format (default if not provided)
			Text = string.IsNullOrEmpty(Format) ? dt.ToString() : dt.ToString(Format);

			// append the time zone label if it is not disabled and if we have one
			if (!string.IsNullOrEmpty(TimeZoneLabel) && OutputTimeZoneLabel)
			{
				Text = "{0} {1}".FormatWith(Text, TimeZoneLabel);
			}

			base.Render(writer);
		}

19 Source : FileExplorer.cs
with MIT License
from aerosoul94

private void PopulateListView(List<DirectoryEntry> dirents, DirectoryEntry parent)
        {
            listView1.BeginUpdate();
            listView1.Items.Clear();

            // Add "up" item
            var upDir = listView1.Items.Add("");

            upDir.SubItems.Add("...");
            if (parent != null)
            {
                if (parent.GetParent() != null)
                {
                    upDir.Tag = new NodeTag(parent.GetParent(), NodeType.Dirent);
                }
                else
                {
                    upDir.Tag = new NodeTag(null, NodeType.Root);
                }
            }
            else
            {
                upDir.Tag = new NodeTag(null, NodeType.Root);
            }

            List<ListViewItem> items = new List<ListViewItem>();
            int index = 1;
            foreach (DirectoryEntry dirent in dirents)
            {
                ListViewItem item = new ListViewItem(index.ToString());
                item.Tag = new NodeTag(dirent, NodeType.Dirent);

                item.SubItems.Add(dirent.FileName);

                DateTime creationTime = dirent.CreationTime.AsDateTime();
                DateTime lastWriteTime = dirent.LastWriteTime.AsDateTime();
                DateTime lastAccessTime = dirent.LastAccessTime.AsDateTime();

                string sizeStr = "";
                if (!dirent.IsDirectory())
                {
                    sizeStr = Utility.FormatBytes(dirent.FileSize);
                }

                item.SubItems.Add(sizeStr);
                item.SubItems.Add(creationTime.ToString());
                item.SubItems.Add(lastWriteTime.ToString());
                item.SubItems.Add(lastAccessTime.ToString());
                item.SubItems.Add("0x" + dirent.Offset.ToString("x"));
                item.SubItems.Add(dirent.Cluster.ToString());

                if (dirent.IsDeleted())
                {
                    item.BackColor = deletedColor;
                }

                index++;

                items.Add(item);
            }

            listView1.Items.AddRange(items.ToArray());
            listView1.EndUpdate();
        }

19 Source : RecoveryResults.cs
with MIT License
from aerosoul94

private void PopulateListView(List<DatabaseFile> dirents, DatabaseFile parent)
        {
            listView1.BeginUpdate();
            listView1.Items.Clear();

            var upDir = listView1.Items.Add("");

            upDir.SubItems.Add("...");
            if (parent != null)
            {
                upDir.Tag = new NodeTag(parent, NodeType.Dirent);
            }
            else
            {
                NodeTag nodeTag = (NodeTag)currentClusterNode.Tag;
                upDir.Tag = new NodeTag(nodeTag.Tag as List<DatabaseFile>, NodeType.Cluster);
            }

            List<ListViewItem> items = new List<ListViewItem>();
            int index = 1;
            foreach (DatabaseFile databaseFile in dirents)
            {
                ListViewItem item = new ListViewItem(index.ToString());
                item.Tag = new NodeTag(databaseFile, NodeType.Dirent);

                item.SubItems.Add(databaseFile.FileName);

                DateTime creationTime = databaseFile.CreationTime.AsDateTime();
                DateTime lastWriteTime = databaseFile.LastWriteTime.AsDateTime();
                DateTime lastAccessTime = databaseFile.LastAccessTime.AsDateTime();

                string sizeStr = "";
                if (!databaseFile.IsDirectory())
                {
                    item.ImageIndex = 1;
                    sizeStr = Utility.FormatBytes(databaseFile.FileSize);
                }
                else
                {
                    item.ImageIndex = 0;
                }

                item.SubItems.Add(sizeStr);
                item.SubItems.Add(creationTime.ToString());
                item.SubItems.Add(lastWriteTime.ToString());
                item.SubItems.Add(lastAccessTime.ToString());
                item.SubItems.Add("0x" + databaseFile.Offset.ToString("x"));
                item.SubItems.Add(databaseFile.Cluster.ToString());

                item.BackColor = statusColor[databaseFile.GetRanking()];

                index++;

                items.Add(item);
            }

            listView1.Items.AddRange(items.ToArray());
            listView1.EndUpdate();
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from Aetsu

public static void LogToFile(string source, string logType, string messsage)
        {
            string FilePath = "log.txt";
            DateTime localDate = DateTime.Now;
            using var fileStream = new FileStream(FilePath, FileMode.Append);
            using var writter = new StreamWriter(fileStream);
            writter.WriteLine("{0} | {1} | {2} -- {3}", localDate.ToString(), logType, source, messsage);
        }

19 Source : ZeroTester.cs
with Mozilla Public License 2.0
from agebullhu

protected override void DoAsync()
        {
            var arg = new MachineEventArg
            {
                EventName = "OpenDoor",
                MachineId = $"Machine-{random.Next()}",
                JsonStr = JsonConvert.SerializeObject(new OpenDoorArg
                {
                    CompanyId ="��˾id",
                    UserType ="�û�����",
                    UserId = random.Next().ToString(),
                    DeviceId ="�豸id",
                    RecordDate=DateTime.Now.ToString(),
                    RecordUserStatus="״̬",
                    InOrOut= $"{((random.Next() % 2) == 1 ? "��" : "��")}",
                    EnterType="������ʽ",
                    PhotoUrl="������",
                    IdenreplacedyImageUrl="֤����",
                    PanoramaUrl="ȫ����",
                    Score="ʶ��ϵ��"
                })
            };
            ApiClient client = new ApiClient
            {
                Station = Station,
                Commmand = Api,
                Argument = JsonConvert.SerializeObject(arg)
            };
            client.CallCommand();
            if (client.State < ZeroOperatorStateType.Failed)
            {
            }
            else if (client.State < ZeroOperatorStateType.Error)
            {
                Interlocked.Increment(ref BlError);
            }
            else if (client.State < ZeroOperatorStateType.TimeOut)
            {
                Interlocked.Increment(ref WkError);
            }
            else if (client.State > ZeroOperatorStateType.LocalNoReady)
            {
                Interlocked.Increment(ref ExError);
            }
            else
            {
                Interlocked.Increment(ref NetError);
            }
        }

19 Source : KLine.cs
with Mozilla Public License 2.0
from agebullhu

public override string ToString()
        {
            return new DateTime(Time* 10000 + 621355968000000000).ToString();
        }

19 Source : ThreadSample.cs
with The Unlicense
from ahotko

public void Go()
        {
            var threadLabor = new ThreadLabor();
            var laborInstructions = new LaborInstructions(syncObject)
            {
                SomeParameter = $"Current DateTime is {DateTime.Now.ToString()}"
            };

            Console.WriteLine("Going into thread...");
            var thread = new Thread(threadLabor.DoWork)
            {
                Priority = ThreadPriority.Highest
            };
            thread.Start(laborInstructions);
            syncObject.WaitOne();
            Console.WriteLine("done!");
        }

19 Source : SettingsSample.cs
with The Unlicense
from ahotko

private void StoreMainSettings()
        {
            Properties.Settings.Default.SettingString = DateTime.Now.ToString();
            Properties.Settings.Default.SettingInt = DateTime.Now.Second;
            Properties.Settings.Default.Save();
        }

19 Source : SettingsSample.cs
with The Unlicense
from ahotko

private void StoreOtherSettings()
        {
            Properties.OtherSettings.Default.SomeOtherStringSetting = DateTime.Now.ToString();
            Properties.OtherSettings.Default.SomeOtherIntSetting = DateTime.Now.Second;
            Properties.OtherSettings.Default.Save();
        }

19 Source : HttpResponse.cs
with GNU General Public License v3.0
from aiportal

private void SetExpires(int minutes)
		{
			if (minutes > 0)
			{
				Response.Headers[HttpResponseHeader.Expires] = DateTime.Now.AddMinutes(minutes).ToString();
			}
			else
			{
				Response.Headers[HttpResponseHeader.Pragma] = "no-cache";
				Response.Headers[HttpResponseHeader.CacheControl] = "no-cache, must-revalidate";
				Response.Headers[HttpResponseHeader.Expires] = DateTime.Now.ToString();
			}
		}

19 Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal

private static string ObjectToString(object obj)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (obj is string) 
				return obj as string;

			Type type = obj.GetType();
			type = Nullable.GetUnderlyingType(type) ?? type;

			string result = null;
			if (type == typeof(Guid))
				result= ((Guid)obj).ToString("n");
			else if (type == typeof(DateTime))
				result=((DateTime)obj).ToString();
			else if (type == typeof(Decimal))
				result=((Decimal)obj).ToString();
			else if (type.IsEnum)
				result= obj.ToString();
			else if (type.IsArray)
				result= ArrayToString(obj);
			else
			{
				var parse = type.GetParseMethod();
				if (parse != null)
					result =obj.ToString();
				else
				{
					if (type.IsValueType && !type.IsPrimitive)
						result = StructToString(obj);
					else
						result= obj.ToString();
				}
			}
			return result;
		}

19 Source : ResponseExtension.cs
with GNU General Public License v3.0
from aiportal

private static void SetExpireTime(HttpListenerResponse resp, int minutes)
		{
			if (minutes == 0)
			{
				resp.Headers[HttpResponseHeader.Pragma] = "no-cache";
				resp.Headers[HttpResponseHeader.CacheControl] = "no-cache, must-revalidate";
			}
			resp.Headers[HttpResponseHeader.Expires] = DateTime.Now.AddMinutes(minutes).ToString();
		}

19 Source : ResponseExtension.cs
with GNU General Public License v3.0
from aiportal

[Conditional("DEBUG")]
		private static void SetDebugMode(HttpListenerResponse resp)
		{
			// no cache
			resp.Headers[HttpResponseHeader.Pragma] = "no-cache";
			resp.Headers[HttpResponseHeader.CacheControl] = "no-cache, must-revalidate";
			resp.Headers[HttpResponseHeader.Expires] = DateTime.Now.ToString();

			// allow other site
			resp.Headers["Access-Control-Allow-Origin"] = "*";

			// plain json result
			if (resp.ContentType == "text/json")
				resp.ContentType = "text/plain";
		}

19 Source : actionChecker.cs
with MIT License
from AlbertMN

[STAThread]
        public void ProcessFile(string file, bool tryingAgain = false) {
            //Custom 'file read delay'
            float fileReadDelay = Properties.Settings.Default.FileReadDelay;
            if (fileReadDelay > 0) {
                MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing...");
                Thread.Sleep((int)fileReadDelay * 1000);
            }

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File doesn't exist (anymore).");
                return;
            }

            //Make sure the file isn't in use before trying to access it
            int tries = 0;
            while (FileInUse(file) || tries >= 20) {
                tries++;
            }
            if (tries >= 20 && FileInUse(file)) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }

            //Check unique file ID (dublicate check)
            ulong theFileUid = 0;
            bool gotFileUid = false;
            tries = 0;
            while (!gotFileUid || tries >= 30) {
                try {
                    theFileUid = getFileUID(file);
                    gotFileUid = true;
                } catch {
                    Thread.Sleep(50);
                }
            }
            if (tries >= 30 && !gotFileUid) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }


            //Validate UID
            if (lastFileUid == 0) {
                lastFileUid = Properties.Settings.Default.LastActionFileUid;
            }
            if (lastFileUid == theFileUid && !tryingAgain) {
                //Often times this function is called three times per file - check if it has already been (or is being) processed
                return;
            }
            if (executedFiles.Contains(theFileUid) && !tryingAgain) {
                MainProgram.DoDebug("Tried to execute an already-executed file (UID " + theFileUid.ToString() + ")");
                return;
            }
            lastFileUid = theFileUid;
            executedFiles.Add(theFileUid);
            Properties.Settings.Default.LastActionFileUid = lastFileUid;
            Properties.Settings.Default.Save();

            MainProgram.DoDebug("Processing file...");
            string originalFileName = file, fullContent = "";

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File no longer exists when trying to read file.");
                return;
            }

            //READ FILE
            if (new FileInfo(file).Length != 0) {
                try {
                    string fileContent;
                    fileContent = File.ReadAllText(file);
                    fullContent = Regex.Replace(fileContent, @"\t|\r", "");
                } catch (Exception e) {
                    if (unsuccessfulReads < 20) {
                        MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)");
                        unsuccessfulReads++;
                        Thread.Sleep(200);
                        ProcessFile(file, true);

                        return;
                    } else {
                        MainProgram.DoDebug("Could not read file on final try; " + e);
                        unsuccessfulReads = 0;
                        return;
                    }
                }
                MainProgram.DoDebug(" - Read complete, content: " + fullContent);
            } else {
                MainProgram.DoDebug(" - File is empty");
                ErrorMessageBox("No action was set in the action file.");
            }
            //END READ

            //DateTime lastModified = File.GetCreationTime(file);
            DateTime lastModified = File.GetLastWriteTime(file);
 
            if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right.

                MainProgram.DoDebug("File creation time: " + lastModified.ToString());
                MainProgram.DoDebug("Local time: " + DateTime.Now.ToString());

                if (GettingStarted.isConfiguringActions) {
                    //Possibly configure an offset - if this always happens

                    Console.WriteLine("File is actually too old, but configuring the software to maybe set an offset");

                    isConfiguringOffset = true;
                    if (lastModifiedOffsets == null) {
                        lastModifiedOffsets = new List<double>();
                    }

                    lastModifiedOffsets.Add((DateTime.Now - lastModified).TotalSeconds);
                    if (lastModifiedOffsets.Count >= 3) {
                        int average = (int)(lastModifiedOffsets.Average());
                        Console.WriteLine("File Margin fixed offset set to; " + average.ToString());
                        Properties.Settings.Default.AutoFileMarginFixer = average;
                        Properties.Settings.Default.Save();
                    }
                } else {
                    bool isGood = false;

                    if (Properties.Settings.Default.AutoFileMarginFixer != 0) {
                        //if (lastModified.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer) < DateTime.Now) {

                        var d1 = lastModified.AddSeconds(-Properties.Settings.Default.FileEditedMargin);
                        var d2 = DateTime.Now.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer);

                        if (d1 < d2) {
                            isGood = true;
                            MainProgram.DoDebug("File timestamp is actually more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, but the software is configured to have an auto-file-margin fix for " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s");
                        } else {
                            //MainProgram.DoDebug(d1.ToString());
                            //MainProgram.DoDebug(d2.ToString());
                            MainProgram.DoDebug("The " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s didn't fix it");
                        }
                    }

                    if (!isGood) {
                        MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed.");
                        new CleanupService().Start();
                        return;
                    }
                }
                //}
            }
            
            MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]");
            MainProgram.DoDebug(" - " + file + " UID; " + theFileUid);
            MainProgram.DoDebug(" - File exists, checking the content...");

            //Process the file
            using (StringReader reader = new StringReader(fullContent)) {
                string theLine = string.Empty;
                do {
                    theLine = reader.ReadLine();
                    if (theLine != null) {
                        MainProgram.DoDebug("\n[EXECUTING ACTION]");
                        CheckAction(theLine, file);
                    }

                } while (theLine != null);
            }

            MainProgram.DoDebug("[ -- DONE -- ]");
        }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
            Exception e = (Exception)args.ExceptionObject;
            string errorLogLoc = Path.Combine(dataFolderLocation, "error_log.txt");

            string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
            RegistryKey thekey = Registry.LocalMachine;
            RegistryKey skey = thekey.OpenSubKey(subKey);

            string windowsVersionName = skey.GetValue("ProductName").ToString();
            string rawWindowsVersion = Environment.OSVersion.ToString();

            int totalExecutions = 0;
            foreach (int action in Properties.Settings.Default.TotalActionsExecuted) {
                totalExecutions += action;
            }
            if (File.Exists(errorLogLoc))
                try {
                    File.Delete(errorLogLoc);
                } catch {
                    DoDebug("Failed to delete error log");
                }

            if (!File.Exists(errorLogLoc)) {
                try {
                    using (var tw = new StreamWriter(errorLogLoc, true)) {
                        tw.WriteLine("OS;");
                        tw.WriteLine("- " + windowsVersionName);
                        tw.WriteLine("- " + rawWindowsVersion);
                        tw.WriteLine();
                        tw.WriteLine("ACC info;");
                        tw.WriteLine("- Version; " + softwareVersion + ", " + releaseDate);
                        tw.WriteLine("- UID; " + Properties.Settings.Default.UID);
                        tw.WriteLine("- Running from; " + currentLocationFull);
                        tw.WriteLine("- Start with Windows; " + (ACCStartsWithWindows() ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Check for updates; " + (Properties.Settings.Default.CheckForUpdates ? "[Yes]" : "[No]"));
                        tw.WriteLine("- In beta program; " + (Properties.Settings.Default.BetaProgram ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Has completed setup guide; " + (Properties.Settings.Default.HasCompletedTutorial ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Check path; " + CheckPath());
                        tw.WriteLine("- Check extension; " + Properties.Settings.Default.ActionFileExtension);
                        tw.WriteLine("- Actions executed; " + totalExecutions);
                        tw.WriteLine("- replacedistant type; " + "[Google replacedistant: " + Properties.Settings.Default.replacedistantType[0] + "] [Alexa: " + Properties.Settings.Default.replacedistantType[1] + "] [Unknown: " + Properties.Settings.Default.replacedistantType[1] + "]");
                        tw.WriteLine();

                        tw.WriteLine(e);
                        tw.Close();
                    }
                } catch {
                    //Caught exception when trying to log exception... *sigh*
                }
            }

            File.AppendAllText(errorLogLoc, DateTime.Now.ToString() + ": " + e + Environment.NewLine);
            if (debug) {
                Console.WriteLine(e);
            }
            MessageBox.Show("A critical error occurred. The developer has been notified and will resolve this issue ASAP! Try and start ACC again, and avoid whatever just made it crash (for now) :)", "ACC | Error");
        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125

public static void InitialiseUpdateCheckingProcess()
        {
            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
            Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
            if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
            {
                new XDoreplacedent(
                        new XElement("CommonVariables")
                    )
                    .Save("Albo1125.Common/CommonVariables.xml");
            }
            try
            {
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
                {

                    try
                    {
                        if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
                        {
                            Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
                            Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
                            return;
                        }
                        DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
                        if (DateTime.Now < UpdateCheckDT)
                        {

                            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
                            return;
                        }
                    }
                    catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }

                }

                
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                GameFiber.StartNew(delegate
                {


                    GetUpdateNodes();
                    foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
                    {
                        CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
                    }
                    if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
                    Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
                });
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

            



        }

19 Source : MKMHelpers.cs
with GNU Affero General Public License v3.0
from alexander-pick

public static void LogError(string subject, string errorMessage, bool popup, string sURL = "")
    {
      lock (errorLogLock)
      {
        // if this the first error of this run, write a header with current date and time in the error log file to know which errors are old and which new
        // monitoring when (if) first error happens helps limit the size of the log in runs when no error happens
        // TODO - maybe clean the log once in a while?
        if (firstError)
        {
          System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetExecutingreplacedembly();
          System.Diagnostics.FileVersionInfo fileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(replacedembly.Location);
          using (var sw = File.AppendText(@".\\error_log.txt"))
          {
            sw.WriteLine(DateTime.Now.ToString() + ", version: " + fileVersionInfo.ProductVersion);
            firstError = false;
          }
        }
        string msg = "Error with " + subject + ": " + errorMessage;
        using (var sw = File.AppendText(@".\\error_log.txt"))
        {
          if (sURL.Length > 0)
            sw.WriteLine(msg + " @ " + sURL);
          else
            sw.WriteLine(msg);
        }
        MainView.Instance.LogMainWindow(msg);

        if (popup)
          MessageBox.Show(msg, "MKMTool encountered error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

19 Source : ScienceExportController.cs
with MIT License
from AlexanderFroemmgen

[HttpPost("export")]
        public IActionResult ExportTrigger([FromBody] ScienceExportDto scienceExport)
        {
            /*
             * Stuff to export:
             * - Database content (outstanding)
             * - Exported folders
             * - Experiment files
             */
            string fileId = $"export{new Random().Next(10000, 99999):000000}";
            using (var stream = new FileStream(_directoryOptions.DataLocation + "Exports/" + fileId + ".zip", FileMode.CreateNew)) {

                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                {
                    using (var file = new StreamWriter(archive.CreateEntry("readme.txt").Open()))
                    {
                        file.Write(scienceExport.Name + "\n\n" + scienceExport.Description + "\n\n");
                        file.Write("This export was generated with MACI version 0.9 at " + DateTime.Now.ToString());
                    }

                    foreach (int id in scienceExport.Experiments)
                    {
                        /* exported replacedysis files for this experiment id */
                        var tmp = _directoryOptions.DataLocation + $"/JupyterNotebook/sim{id:0000}";
                        foreach (var fileEntry in _directoryOptions.GetAllFilesRecursively(tmp))
                        {
                            archive.CreateEntryFromFile(fileEntry, $"JupyterNotebooks/sim{id:0000}/{fileEntry}");
                        }

                        // TODO copy experiment framework stuff to avoid overriding stuff
                        /* export experiment files */
                        var experiment = _context.Experiments.Where(s => id == s.Id).SingleOrDefault();
                        var tmp2 = _directoryOptions.DataLocation + $"/ExperimentFramework/" + experiment.FileName;
                        foreach (var fileEntry in _directoryOptions.GetAllFilesRecursively(tmp2))
                        {
                            archive.CreateEntryFromFile(fileEntry, $"ExperimentFramework/sim{id:0000}/{fileEntry}");
                        }
                    }
                }
                stream.Flush();
            }
            
            return Json(new
            {
                Name = fileId
            });
        }

19 Source : OptimizerMaster.cs
with Apache License 2.0
from AlexWan

public string GetSaveString()
        {
            string result = "";

            result += TypeFaze.ToString() + "%";

            result += _timeStart.ToString() + "%";

            result += _timeEnd.ToString() + "%";

            result += Days.ToString() + "%";

            return result;
        }

19 Source : Helpers.cs
with MIT License
from Alkl58

public static void Logging(string log)
        {
            // Logging Function
            if (MainWindow.Logging)
            {
                DateTime starttime = DateTime.Now;
                WriteToFileThreadSafe(starttime.ToString() + " : " + log, Global.Video_Output + ".log");
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from aloopkin

private static bool IsThereCertificateAndIsItToBeRenewed(List<string> domains)
        {
            string certificateExpirationDate = _config.ReadStringParameter("certExpDate" + Utils.DomainsToHostId(domains));
            _logger.Debug($"Current certificate expiration date is: {certificateExpirationDate}");
            if ((certificateExpirationDate == null) || (certificateExpirationDate.Length == 0)) return true;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            DateTime expirationDate = DateTime.Parse(certificateExpirationDate);
            DateTime futureThresold = DateTime.Now.AddDays(_config.ReadIntParameter("renewalDays", 30));
            _logger.Debug($"Expiration Thresold Date after delay: {futureThresold.ToString()}");
            if (futureThresold > expirationDate) return true;
            _logger.Debug("Certificate exists and does not need to be renewed");
            return false;
        }

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveSystemInfo (string path) {
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				temporaryPath = path;
			} else {
				temporaryPath = path;
			}
			i = 0;
				sysInfo.Add("--- SystemInfo --- ");
				sysInfo.Add("Battery Level: " + (SystemInfo.batteryLevel *100) + "%");
				sysInfo.Add("Battery Status: " + SystemInfo.batteryStatus.ToString());
				sysInfo.Add("Copy Texture Support: " + SystemInfo.copyTextureSupport.ToString());
				sysInfo.Add("Device Model: " + SystemInfo.deviceModel);
				sysInfo.Add("Device Name: " + SystemInfo.deviceName);
				sysInfo.Add("Device Type: " + SystemInfo.deviceType.ToString());
				sysInfo.Add("Unique Device ID: " + SystemInfo.deviceUniqueIdentifier);
				sysInfo.Add("Graphics Device ID: " + SystemInfo.graphicsDeviceID);
				sysInfo.Add("Graphics Device Name: " + SystemInfo.graphicsDeviceName);
				sysInfo.Add("Graphics Device Type: " + SystemInfo.graphicsDeviceType.ToString());
				sysInfo.Add("Graphics Device Vendor: " + SystemInfo.graphicsDeviceVendor);
				sysInfo.Add("Graphics Device VendorID: " + SystemInfo.graphicsDeviceVendorID);
				sysInfo.Add("Graphics Device Version: " + SystemInfo.graphicsDeviceVersion);
				sysInfo.Add("Graphics Memory Size: " + SystemInfo.graphicsMemorySize);//
				sysInfo.Add("Graphics Mulreplacedhreaded: " + SystemInfo.graphicsMulreplacedhreaded);
				sysInfo.Add("Graphics Shader Level: " + SystemInfo.graphicsShaderLevel);
				sysInfo.Add("Graphics UV Starts at Top?: " + SystemInfo.graphicsUVStartsAtTop);
				sysInfo.Add("Max Cubemap Size: " + SystemInfo.maxCubemapSize);
				sysInfo.Add("Max Texture Size: " + SystemInfo.maxTextureSize);
				sysInfo.Add("NPOT Support: " + SystemInfo.npotSupport.ToString());
				sysInfo.Add("OS: " + SystemInfo.operatingSystem);
				sysInfo.Add("OS Family: " + SystemInfo.operatingSystemFamily.ToString());
				sysInfo.Add("Processor Count: " + SystemInfo.processorCount);
				sysInfo.Add("Processor Frequency: " + SystemInfo.processorFrequency + "MHz");
				sysInfo.Add("Processor Type: " + SystemInfo.processorType);
				sysInfo.Add("Supported Render Targer Count: " + SystemInfo.supportedRenderTargetCount);
				if(SystemInfo.supports2DArrayTextures){sysInfo.Add("Supports 2D Array Textures : Yes");} else { sysInfo.Add("Supports 2D Array Textures : No");}
				if(SystemInfo.supports3DRenderTextures){sysInfo.Add("Supports 3D Render Textures : Yes");} else { sysInfo.Add("Supports 3D Render Textures : No");}
				if(SystemInfo.supports3DTextures){sysInfo.Add("Supports 3D Textures : Yes");} else { sysInfo.Add("Supports 3D Textures : No");}
				if(SystemInfo.supportsAccelerometer){sysInfo.Add("Supports Accelerometer : Yes");} else { sysInfo.Add("Supports Accelerometer : No");}
				if(SystemInfo.supportsAudio){sysInfo.Add("Supports Audio : Yes");} else { sysInfo.Add("Supports Audio : No");}
				if(SystemInfo.supportsComputeShaders){sysInfo.Add("Supports Compute Shaders : Yes");} else { sysInfo.Add("Supports Compute Shaders : No");}
				if(SystemInfo.supportsCubemapArrayTextures){sysInfo.Add("Supports Cubemap Array Textures : Yes");} else { sysInfo.Add("Supports Cubemap Array Textures : No");}
				if(SystemInfo.supportsGyroscope){sysInfo.Add("Supports Gyroscope : Yes");} else { sysInfo.Add("Supports Gyroscope : No");}
				if(SystemInfo.supportsImageEffects){sysInfo.Add("Supports Image Effects : Yes");} else { sysInfo.Add("Supports Image Effects : No");}
				if(SystemInfo.supportsInstancing){sysInfo.Add("Supports Instancing : Yes");} else { sysInfo.Add("Supports Instancing : No");}
				if(SystemInfo.supportsLocationService){sysInfo.Add("Supports Location Services : Yes");} else { sysInfo.Add("Supports Location Services : No");}
				if(SystemInfo.supportsMotionVectors){sysInfo.Add("Supports Motion Vectors : Yes");} else { sysInfo.Add("Supports Motion Vectors : No");}
				if(SystemInfo.supportsRawShadowDepthSampling){sysInfo.Add("Supports Raw Shadow Depth Sampling : Yes");} else { sysInfo.Add("Supports Raw Shadow Depth Sampling : No");}
				if(SystemInfo.supportsRenderToCubemap){sysInfo.Add("Supports Render To Cubemap : Yes");} else { sysInfo.Add("Supports Render To Cubemap : No");}
				if(SystemInfo.supportsShadows){sysInfo.Add("Supports Shadows : Yes");} else { sysInfo.Add("Supports Shadows : No");}
				if(SystemInfo.supportsSparseTextures){sysInfo.Add("Supports Sparse Textures : Yes");} else { sysInfo.Add("Supports Sparse Textures : No");}
				if(SystemInfo.supportsVibration){sysInfo.Add("Supports Vibration : Yes");} else { sysInfo.Add("Supports Vibration : No");}
				sysInfo.Add("System Memory Size: " + SystemInfo.systemMemorySize);
				sysInfo.Add("Unsupported Identifier: " + SystemInfo.unsupportedIdentifier);
				if(SystemInfo.usesReversedZBuffer){sysInfo.Add("Uses Reversed Z Buffer : Yes");} else { sysInfo.Add("Uses Reversed Z Buffer : No");}
				sysInfo.Add(string.Format("{0} {1}", "", System.Environment.NewLine));
				sysInfo.Add("--- " + System.DateTime.Now.ToString()+" ---" );
				WriteDataToFile(false);
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveSystemInfo (string path, bool openDir) {
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				temporaryPath = path;
			} else {
				temporaryPath = path;
			}
			i = 0;
				sysInfo.Add("--- SystemInfo --- ");
				sysInfo.Add("Battery Level: " + (SystemInfo.batteryLevel *100) + "%");
				sysInfo.Add("Battery Status: " + SystemInfo.batteryStatus.ToString());
				sysInfo.Add("Copy Texture Support: " + SystemInfo.copyTextureSupport.ToString());
				sysInfo.Add("Device Model: " + SystemInfo.deviceModel);
				sysInfo.Add("Device Name: " + SystemInfo.deviceName);
				sysInfo.Add("Device Type: " + SystemInfo.deviceType.ToString());
				sysInfo.Add("Unique Device ID: " + SystemInfo.deviceUniqueIdentifier);
				sysInfo.Add("Graphics Device ID: " + SystemInfo.graphicsDeviceID);
				sysInfo.Add("Graphics Device Name: " + SystemInfo.graphicsDeviceName);
				sysInfo.Add("Graphics Device Type: " + SystemInfo.graphicsDeviceType.ToString());
				sysInfo.Add("Graphics Device Vendor: " + SystemInfo.graphicsDeviceVendor);
				sysInfo.Add("Graphics Device VendorID: " + SystemInfo.graphicsDeviceVendorID);
				sysInfo.Add("Graphics Device Version: " + SystemInfo.graphicsDeviceVersion);
				sysInfo.Add("Graphics Memory Size: " + SystemInfo.graphicsMemorySize);//
				sysInfo.Add("Graphics Mulreplacedhreaded: " + SystemInfo.graphicsMulreplacedhreaded);
				sysInfo.Add("Graphics Shader Level: " + SystemInfo.graphicsShaderLevel);
				sysInfo.Add("Graphics UV Starts at Top?: " + SystemInfo.graphicsUVStartsAtTop);
				sysInfo.Add("Max Cubemap Size: " + SystemInfo.maxCubemapSize);
				sysInfo.Add("Max Texture Size: " + SystemInfo.maxTextureSize);
				sysInfo.Add("NPOT Support: " + SystemInfo.npotSupport.ToString());
				sysInfo.Add("OS: " + SystemInfo.operatingSystem);
				sysInfo.Add("OS Family: " + SystemInfo.operatingSystemFamily.ToString());
				sysInfo.Add("Processor Count: " + SystemInfo.processorCount);
				sysInfo.Add("Processor Frequency: " + SystemInfo.processorFrequency + "MHz");
				sysInfo.Add("Processor Type: " + SystemInfo.processorType);
				sysInfo.Add("Supported Render Targer Count: " + SystemInfo.supportedRenderTargetCount);
				if(SystemInfo.supports2DArrayTextures){sysInfo.Add("Supports 2D Array Textures : Yes");} else { sysInfo.Add("Supports 2D Array Textures : No");}
				if(SystemInfo.supports3DRenderTextures){sysInfo.Add("Supports 3D Render Textures : Yes");} else { sysInfo.Add("Supports 3D Render Textures : No");}
				if(SystemInfo.supports3DTextures){sysInfo.Add("Supports 3D Textures : Yes");} else { sysInfo.Add("Supports 3D Textures : No");}
				if(SystemInfo.supportsAccelerometer){sysInfo.Add("Supports Accelerometer : Yes");} else { sysInfo.Add("Supports Accelerometer : No");}
				if(SystemInfo.supportsAudio){sysInfo.Add("Supports Audio : Yes");} else { sysInfo.Add("Supports Audio : No");}
				if(SystemInfo.supportsComputeShaders){sysInfo.Add("Supports Compute Shaders : Yes");} else { sysInfo.Add("Supports Compute Shaders : No");}
				if(SystemInfo.supportsCubemapArrayTextures){sysInfo.Add("Supports Cubemap Array Textures : Yes");} else { sysInfo.Add("Supports Cubemap Array Textures : No");}
				if(SystemInfo.supportsGyroscope){sysInfo.Add("Supports Gyroscope : Yes");} else { sysInfo.Add("Supports Gyroscope : No");}
				if(SystemInfo.supportsImageEffects){sysInfo.Add("Supports Image Effects : Yes");} else { sysInfo.Add("Supports Image Effects : No");}
				if(SystemInfo.supportsInstancing){sysInfo.Add("Supports Instancing : Yes");} else { sysInfo.Add("Supports Instancing : No");}
				if(SystemInfo.supportsLocationService){sysInfo.Add("Supports Location Services : Yes");} else { sysInfo.Add("Supports Location Services : No");}
				if(SystemInfo.supportsMotionVectors){sysInfo.Add("Supports Motion Vectors : Yes");} else { sysInfo.Add("Supports Motion Vectors : No");}
				if(SystemInfo.supportsRawShadowDepthSampling){sysInfo.Add("Supports Raw Shadow Depth Sampling : Yes");} else { sysInfo.Add("Supports Raw Shadow Depth Sampling : No");}
				if(SystemInfo.supportsRenderToCubemap){sysInfo.Add("Supports Render To Cubemap : Yes");} else { sysInfo.Add("Supports Render To Cubemap : No");}
				if(SystemInfo.supportsShadows){sysInfo.Add("Supports Shadows : Yes");} else { sysInfo.Add("Supports Shadows : No");}
				if(SystemInfo.supportsSparseTextures){sysInfo.Add("Supports Sparse Textures : Yes");} else { sysInfo.Add("Supports Sparse Textures : No");}
				if(SystemInfo.supportsVibration){sysInfo.Add("Supports Vibration : Yes");} else { sysInfo.Add("Supports Vibration : No");}
				sysInfo.Add("System Memory Size: " + SystemInfo.systemMemorySize);
				sysInfo.Add("Unsupported Identifier: " + SystemInfo.unsupportedIdentifier);
				if(SystemInfo.usesReversedZBuffer){sysInfo.Add("Uses Reversed Z Buffer : Yes");} else { sysInfo.Add("Uses Reversed Z Buffer : No");}
				sysInfo.Add("--- " + System.DateTime.Now.ToString()+" ---" );
				sysInfo.Add(string.Format("{0} {1}", "", System.Environment.NewLine));
				WriteDataToFile(openDir);
		}

19 Source : EFormidlingClientUnitTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public void Verify_Arkivmelding_Build()
        {        
            Arkivmelding arkivmelding = new Arkivmelding
            {
                AntallFiler = 1,
                Tidspunkt = DateTime.Now.ToString(),
                MeldingId = Guid.NewGuid().ToString(),
                System = "LandLord",
                Mappe = new List<Mappe>
                {
                    new Mappe
                    {
                        SystemID = Guid.NewGuid().ToString(),
                        replacedtel = "Dette er en replacedtel",
                        OpprettetDato = DateTime.Now.ToString(),
                        Type = "saksmappe",
                        Basisregistrering = new Basisregistrering
                         {
                            Type = "journalpost",
                            SystemID = Guid.NewGuid().ToString(),
                            OpprettetDato = DateTime.UtcNow,
                            OpprettetAv = "LandLord",
                            ArkivertDato = DateTime.Now,
                            ArkivertAv = "LandLord",
                            Dokumentbeskrivelse = new Dokumentbeskrivelse
                            {
                                SystemID = Guid.NewGuid().ToString(),
                                Dokumenttype = "Bestilling",
                                Dokumentstatus = "Dokumentet er ferdigstilt",
                                replacedtel = "Hei",
                                OpprettetDato = DateTime.UtcNow,
                                OpprettetAv = "LandLord",
                                TilknyttetRegistreringSom = "hoveddokument",
                                Dokumentnummer = 1,
                                TilknyttetDato = DateTime.Now,
                                TilknyttetAv = "Landlord",
                                Dokumentobjekt = new Dokumentobjekt
                                {
                                    Versjonsnummer = 1,
                                    Variantformat = "Produksjonsformat",
                                    OpprettetDato = DateTime.UtcNow,
                                    OpprettetAv = "LandLord",
                                    ReferanseDokumentfil = "skjema.xml",
                                },
                            },
                            replacedtel = "Nye lysrør",
                            Offentligreplacedtel = "Nye lysrør",
                            Journalposttype = "Utgående dokument",
                            Journalstatus = "Journalført",
                            Journaldato = DateTime.Now,
                         },
                    },
                },
            };

            MemoryStream stream = new MemoryStream();
            XmlSerializer serializer = new XmlSerializer(typeof(Arkivmelding));
            serializer.Serialize(stream, arkivmelding);

            using (MemoryStream ms = stream)
            {
                stream.Seek(0, SeekOrigin.Begin);
                var verifiedArkivmelding = serializer.Deserialize(stream) as Arkivmelding;

                replacedert.NotNull(arkivmelding);
                replacedert.Equal(typeof(Arkivmelding), arkivmelding.GetType());
            }
        }

19 Source : App.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public override async Task<(string, Stream)> GenerateEFormidlingMetadata(Instance instance)
        {
            Arkivmelding arkivmelding = new Arkivmelding
            {
                AntallFiler = 1,
                Tidspunkt = DateTime.Now.ToString(),
                MeldingId = Guid.NewGuid().ToString(),
                System = "LandLord",
                Mappe = new List<Mappe>
                {
                    new Mappe
                    {
                        SystemID = Guid.NewGuid().ToString(),
                        replacedtel = "Dette er en replacedtel",
                        OpprettetDato = DateTime.Now.ToString(),
                        Type = "saksmappe",
                        Basisregistrering = new Basisregistrering
                        {
                            Type = "journalpost",
                            SystemID = Guid.NewGuid().ToString(),
                            OpprettetDato = DateTime.UtcNow,
                            OpprettetAv = "LandLord",
                            ArkivertDato = DateTime.Now,
                            ArkivertAv = "LandLord",
                            Dokumentbeskrivelse = new Dokumentbeskrivelse
                            {
                                SystemID = Guid.NewGuid().ToString(),
                                Dokumenttype = "Bestilling",
                                Dokumentstatus = "Dokumentet er ferdigstilt",
                                replacedtel = "Hei",
                                OpprettetDato = DateTime.UtcNow,
                                OpprettetAv = "LandLord",
                                TilknyttetRegistreringSom = "hoveddokument",
                                Dokumentnummer = 1,
                                TilknyttetDato = DateTime.Now,
                                TilknyttetAv = "Landlord",
                                Dokumentobjekt = new Dokumentobjekt
                                {
                                    Versjonsnummer = 1,
                                    Variantformat = "Produksjonsformat",
                                    OpprettetDato = DateTime.UtcNow,
                                    OpprettetAv = "LandLord",
                                    ReferanseDokumentfil = "skjema.xml"
                                },
                            },
                            replacedtel = "Nye lysrør",
                            Offentligreplacedtel = "Nye lysrør",
                            Journalposttype = "Utgående dokument",
                            Journalstatus = "Journalført",
                            Journaldato = DateTime.Now
                        },
                    },
                },
            };

            MemoryStream stream = new MemoryStream();

            XmlSerializer serializer = new XmlSerializer(typeof(Arkivmelding));

            serializer.Serialize(stream, arkivmelding);
            stream.Position = 0;

            StreamContent streamContent = new StreamContent(stream);
            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");

            return await Task.FromResult(("arkivmelding.xml", stream));
        }

19 Source : PolicyRepositoryMock.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private async Task<Response<BlobContentInfo>> WriteStreamToTestDataFolder(string filepath, Stream fileStream)
        {
            string dataPath = GetDataBlobPath() + filepath;

            if (!Directory.Exists(Path.GetDirectoryName(dataPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dataPath));
            }

            int filesize;

            using (Stream streamToWriteTo = File.Open(dataPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                await fileStream.CopyToAsync(streamToWriteTo);
                streamToWriteTo.Flush();
                filesize = (int)streamToWriteTo.Length;
            }

            BlobContentInfo mockedBlobInfo = BlobsModelFactory.BlobContentInfo(new ETag("ETagSuccess"), DateTime.Now, new byte[1], DateTime.Now.ToUniversalTime().ToString(), "encryptionKeySha256", "encryptionScope", 1);
            Mock<Response<BlobContentInfo>> mockResponse = new Mock<Response<BlobContentInfo>>();
            mockResponse.SetupGet(r => r.Value).Returns(mockedBlobInfo);

            Mock<Response> responseMock = new Mock<Response>();
            responseMock.SetupGet(r => r.Status).Returns((int)HttpStatusCode.Created);
            mockResponse.Setup(r => r.GetRawResponse()).Returns(responseMock.Object);

            return mockResponse.Object;
        }

19 Source : HomeController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public async Task<IActionResult> Login()
        {
            string userName = string.Empty;
            string goToUrl = "/";

            // Verify that user is not logged in already.
            if (!string.IsNullOrEmpty(AuthenticationHelper.GetDeveloperUserName(HttpContext)))
            {
                return LocalRedirect(goToUrl);
            }

            // Temporary catch errors until we figure out how to force this.
            try
            {
                userName = await _giteaApi.GetUserNameFromUI();
                if (string.IsNullOrEmpty(userName))
                {
                    return (Environment.GetEnvironmentVariable("ServiceRepositorySettings__GiteaLoginUrl") != null)
                    ? Redirect(Environment.GetEnvironmentVariable("ServiceRepositorySettings__GiteaLoginUrl"))
                    : Redirect(_settings.GiteaLoginUrl);
                }
            }
            catch (Exception ex)
            {
                return Content(ex.ToString());
            }

            _logger.LogInformation("Updating app key for " + userName);
            KeyValuePair<string, string> accessKeyValuePair = await _giteaApi.GetSessionAppKey() ?? default(KeyValuePair<string, string>);
            List<Claim> claims = new List<Claim>();
            const string Issuer = "https://altinn.no";
            if (!accessKeyValuePair.Equals(default(KeyValuePair<string, string>)))
            {
                string accessToken = accessKeyValuePair.Value;
                string accessId = accessKeyValuePair.Key;
                _logger.LogInformation("Adding key to claims: " + accessId);
                claims.Add(new Claim(AltinnCoreClaimTypes.DeveloperToken, accessToken, ClaimValueTypes.String, Issuer));
                claims.Add(new Claim(AltinnCoreClaimTypes.DeveloperTokenId, accessId, ClaimValueTypes.String, Issuer));
            }

            claims.Add(new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, Issuer));
            ClaimsIdenreplacedy idenreplacedy = new ClaimsIdenreplacedy("TestUserLogin");
            idenreplacedy.AddClaims(claims);

            ClaimsPrincipal principal = new ClaimsPrincipal(idenreplacedy);

            string timeoutString = DateTime.UtcNow.AddMinutes(_generalSettings.SessionDurationInMinutes - 5).ToString();
            HttpContext.Response.Cookies.Append(
                _generalSettings.SessionTimeoutCookieName,
                timeoutString,
                new CookieOptions { HttpOnly = true });

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                principal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(_generalSettings.SessionDurationInMinutes),
                    IsPersistent = false,
                    AllowRefresh = false,
                });

            return LocalRedirect(goToUrl);
        }

See More Examples