/// <summary> /// [异步async]上传文件 /// </summary> /// <param name="localFile">本地待上传的文件名</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public async Task <HttpResult> UploadFileAsync(StorageFile localFile, string saveKey, string token) { HttpResult result = new HttpResult(); var fi = await localFile.GetBasicPropertiesAsync(); if (fi.Size > (ulong)PUT_THRESHOLD) { if (recordFile == null) { string recordKey = ResumeHelper.GetDefaultRecordKey(localFile.Path, saveKey); recordFile = await(await UserEnv.GetHomeFolderAsync()).CreateFileAsync(recordKey, CreationCollisionOption.OpenIfExists); } if (upph == null) { upph = new UploadProgressHandler(ResumableUploader.DefaultUploadProgressHandler); } if (upctl == null) { upctl = new UploadController(ResumableUploader.DefaultUploadController); } ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN, CHUNK_UNIT); result = await ru.UploadFileAsync(localFile, saveKey, token, recordFile, upph, upctl); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadFileAsync(localFile, saveKey, token); } return(result); }
/// <summary> /// [异步async]上传文件 /// </summary> /// <param name="localFile">本地待上传的文件名</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public async Task <HttpResult> UploadFileAsync(string localFile, string saveKey, string token) { HttpResult result = new HttpResult(); var fi = new FileInfo(localFile); if (fi.Length > PUT_THRESHOLD) { if (recordFile == null) { string recordKey = ResumeHelper.GetDefaultRecordKey(localFile, saveKey); recordFile = Path.Combine(UserEnv.GetHomeFolder(), recordKey); } if (upph == null) { upph = new UploadProgressHandler(ResumableUploader.DefaultUploadProgressHandler); } if (upctl == null) { upctl = new UploadController(ResumableUploader.DefaultUploadController); } ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN, CHUNK_UNIT); result = await ru.UploadFileAsync(localFile, saveKey, token, recordFile, upph, upctl); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadFileAsync(localFile, saveKey, token); } return(result); }
CreateEnvJson() { // collecet search paths var searchPaths = new List <string>() { PyRevitConsts.DefaultExtensionsPath }; searchPaths.AddRange(PyRevitExtensions.GetRegisteredExtensionSearchPaths()); // collect list of lookup sources var lookupSrc = new List <string>() { PyRevitExtensions.GetDefaultExtensionLookupSource() }; lookupSrc.AddRange(PyRevitExtensions.GetRegisteredExtensionLookupSources()); // create json data object var jsonData = new Dictionary <string, object>() { { "meta", new Dictionary <string, object>() { { "version", "0.1.0" } } }, { "clones", PyRevitClones.GetRegisteredClones() }, { "attachments", PyRevitAttachments.GetAttachments() }, { "extensions", PyRevitExtensions.GetInstalledExtensions() }, { "searchPaths", searchPaths }, { "lookupSources", lookupSrc }, { "installed", RevitProduct.ListInstalledProducts() }, { "running", RevitController.ListRunningRevits() }, { "pyrevitDataDir", PyRevitLabsConsts.PyRevitPath }, { "userEnv", new Dictionary <string, object>() { { "osVersion", UserEnv.GetWindowsVersion() }, { "execUser", string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName) }, { "activeUser", UserEnv.GetLoggedInUserName() }, { "isAdmin", UserEnv.IsRunAsAdmin() }, { "userAppdata", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) }, { "latestFramework", UserEnv.GetInstalledDotNetVersion() }, { "targetPacks", UserEnv.GetInstalledDotnetTargetPacks() }, { "targetPacksCore", UserEnv.GetInstalledDotnetCoreTargetPacks() }, { "cliVersion", PyRevitCLI.CLIVersion }, } }, }; var jsonExportCfg = new JsonSerializerSettings { Error = delegate(object sender, pyRevitLabs.Json.Serialization.ErrorEventArgs args) { args.ErrorContext.Handled = true; }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; jsonExportCfg.Converters.Add(new JsonVersionConverter()); return(JsonConvert.SerializeObject(jsonData, jsonExportCfg)); }
public TelemetryRecord() { meta = new Dictionary <string, string> { { "schema", "2.0" }, }; timestamp = Telemetry.GetTelemetryTimeStamp(); host_user = UserEnv.GetLoggedInUserName(); }
private static ScriptTelemetryRecord MakeTelemetryRecord(ref ScriptRuntime runtime) { // determine build number string revitbuild = "20000101_0000(x64)"; #if (REVIT2013 || REVIT2014 || REVIT2015 || REVIT2016 || REVIT2017 || REVIT2018 || REVIT2019 || REVIT2020) revitbuild = runtime.App.VersionBuild; #else // Revit 2021 has a bug on .VersionBuild // it reports identical value as .VersionNumber // let's give a invalid, but correctly formatted value to the telemetry server string revitExePath = Process.GetCurrentProcess().MainModule.FileName; if (revitExePath != null && revitExePath != string.Empty) { HostProductInfo pinfo = RevitProductData.GetBinaryProductInfo(revitExePath); if (pinfo.build != null && pinfo.build != string.Empty) { revitbuild = string.Format("{0}({1})", pinfo.build, pinfo.target); } } #endif // setup a new telemetry record return(new ScriptTelemetryRecord { host_user = UserEnv.GetLoggedInUserName(), username = runtime.App.Username, revit = runtime.App.VersionNumber, revitbuild = revitbuild, sessionid = runtime.SessionUUID, pyrevit = runtime.PyRevitVersion, clone = runtime.CloneName, debug = runtime.ScriptRuntimeConfigs.DebugMode, config = runtime.ScriptRuntimeConfigs.ConfigMode, from_gui = runtime.ScriptRuntimeConfigs.ExecutedFromUI, exec_id = runtime.ExecId, exec_timestamp = runtime.ExecTimestamp, commandname = runtime.ScriptData.CommandName, commandbundle = runtime.ScriptData.CommandBundle, commandextension = runtime.ScriptData.CommandExtension, commanduniquename = runtime.ScriptData.CommandUniqueId, scriptpath = runtime.ScriptSourceFile, docname = runtime.DocumentName, docpath = runtime.DocumentPath, resultcode = runtime.ExecutionResult, commandresults = runtime.GetResultsDictionary(), trace = new ScriptTelemetryRecordTraceInfo { engine = new ScriptTelemetryRecordEngineInfo { type = runtime.EngineType.ToString().ToLower(), version = runtime.EngineVersion, syspath = runtime.ScriptRuntimeConfigs.SearchPaths, configs = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(runtime.ScriptRuntimeConfigs.EngineConfigs), }, message = runtime.TraceMessage } }); }
public static string GetRevitAddonsFilePath(int revitYear, string addinFileName, bool allusers = false) { if (UserEnv.IsRunAsElevated()) { allusers = true; } var rootFolder = allusers ? System.Environment.SpecialFolder.CommonApplicationData : System.Environment.SpecialFolder.ApplicationData; return(Path.Combine(GetRevitAddonsFolder(revitYear, allUsers: allusers), addinFileName + ".addin")); }
public static UserEnv GetUserEnvByUserID(int UserID) { UserEnv userEnv = new UserEnv(); using (SqlConnection Cnx = new SqlConnection(ConfigurationManager.ConnectionStrings["Atreemo_Cnx"].ConnectionString)) { SqlCommand Cmd = new SqlCommand("SELECT CAST(DefaultEnv AS INT) DefaultEnv,UserID,UserName FROM aclUsers WITH (NOLOCK) WHERE UserID = " + UserID + " AND ApplicationName LIKE '" + ConfigurationManager.AppSettings["ApplicationName"].ToString() + "'", Cnx); Cmd.CommandTimeout = 3600; Cnx.Open(); SqlDataReader Dr = Cmd.ExecuteReader(); while (Dr.Read()) { userEnv.UserID = (int)Dr["UserID"]; userEnv.DefaultEnv = (int)Dr["DefaultEnv"]; userEnv.UserName = (string)Dr["UserName"]; } Cnx.Close(); } return(userEnv); }
PrinUserEnv() { PrintHeader("User Environment"); Console.WriteLine(UserEnv.GetWindowsVersion()); Console.WriteLine(string.Format("Executing User: {0}\\{1}", Environment.UserDomainName, Environment.UserName)); Console.WriteLine(string.Format("Active User: {0}", UserEnv.GetLoggedInUserName())); Console.WriteLine(string.Format("Admin Access: {0}", UserEnv.IsRunAsAdmin() ? "Yes" : "No")); Console.WriteLine(string.Format("%APPDATA%: \"{0}\"", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))); Console.WriteLine(string.Format("Latest Installed .Net Framework: {0}", UserEnv.GetInstalledDotNetVersion())); try { string targetPacks = ""; foreach (string targetPackagePath in UserEnv.GetInstalledDotnetTargetPacks()) { targetPacks += string.Format("{0} ", Path.GetFileName(targetPackagePath)); } Console.WriteLine(string.Format("Installed .Net Target Packs: {0}", targetPacks)); } catch { Console.WriteLine("No .Net Target Packs are installed."); } try { string targetPacks = ""; foreach (string targetPackagePath in UserEnv.GetInstalledDotnetCoreTargetPacks()) { targetPacks += string.Format("v{0} ", Path.GetFileName(targetPackagePath)); } Console.WriteLine(string.Format("Installed .Net-Core Target Packs: {0}", targetPacks)); } catch { Console.WriteLine("No .Ne-Core Target Packs are installed."); } Console.WriteLine(string.Format("pyRevit CLI {0}", PyRevitCLI.CLIVersion.ToString())); }
private static ScriptTelemetryRecord MakeTelemetryRecord(ref ScriptRuntime runtime) { // setup a new telemetry record return(new ScriptTelemetryRecord { host_user = UserEnv.GetLoggedInUserName(), username = Telemetry.GetRevitUser(runtime.App), revit = Telemetry.GetRevitVersion(runtime.App), revitbuild = Telemetry.GetRevitBuild(runtime.App), sessionid = runtime.SessionUUID, pyrevit = runtime.PyRevitVersion, clone = runtime.CloneName, debug = runtime.ScriptRuntimeConfigs.DebugMode, config = runtime.ScriptRuntimeConfigs.ConfigMode, from_gui = runtime.ScriptRuntimeConfigs.ExecutedFromUI, exec_id = runtime.ExecId, exec_timestamp = runtime.ExecTimestamp, commandname = runtime.ScriptData.CommandName, commandbundle = runtime.ScriptData.CommandBundle, commandextension = runtime.ScriptData.CommandExtension, commanduniquename = runtime.ScriptData.CommandUniqueId, scriptpath = runtime.ScriptSourceFile, docname = runtime.DocumentName, docpath = runtime.DocumentPath, resultcode = runtime.ExecutionResult, commandresults = runtime.GetResultsDictionary(), trace = new ScriptTelemetryRecordTraceInfo { engine = new ScriptTelemetryRecordEngineInfo { type = runtime.EngineType.ToString().ToLower(), version = runtime.EngineVersion, syspath = runtime.ScriptRuntimeConfigs.SearchPaths, configs = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(runtime.ScriptRuntimeConfigs.EngineConfigs), }, message = runtime.TraceMessage } }); }
DownloadReleaseAsset(PyRevitReleaseAssetType assetType, string destPath, string searchPattern, bool latest = false, bool listPreReleases = false) { // get dest path if (destPath == null) { destPath = UserEnv.GetPath(KnownFolder.Downloads); } PyRevitRelease matchedRelease = null; // determine latest release if (latest) { matchedRelease = PyRevitRelease.GetLatestRelease(includePreRelease: listPreReleases); if (matchedRelease == null) { throw new pyRevitException("Can not determine latest release."); } } // or find first release matching given pattern else { if (searchPattern != null) { matchedRelease = PyRevitRelease.FindReleases(searchPattern, includePreRelease: listPreReleases).First(); } if (matchedRelease == null) { throw new pyRevitException( string.Format("No release matching \"{0}\" were found.", searchPattern) ); } } // grab download url string downloadUrl = null; switch (assetType) { case PyRevitReleaseAssetType.Archive: downloadUrl = matchedRelease.ArchiveUrl; break; case PyRevitReleaseAssetType.Installer: downloadUrl = matchedRelease.InstallerUrl; break; case PyRevitReleaseAssetType.Unknown: downloadUrl = null; break; } if (downloadUrl != null) { logger.Debug("Downloading release package from \"{0}\"", downloadUrl); // ensure destpath is to a file if (CommonUtils.VerifyPath(destPath)) { destPath = Path.Combine(destPath, Path.GetFileName(downloadUrl)).NormalizeAsPath(); } logger.Debug("Saving package to \"{0}\"", destPath); // download file and report CommonUtils.DownloadFile(downloadUrl, destPath); Console.WriteLine( string.Format("Downloaded package to \"{0}\"", destPath) ); } }
public static void StartAsActiveUser(this Process process) { // Sanity check. if (process.StartInfo == null) { throw new InvalidOperationException("The StartInfo property must be defined"); } if (string.IsNullOrEmpty(process.StartInfo.FileName)) { throw new InvalidOperationException("The StartInfo.FileName property must be defined"); } // Retrieve the active session ID and its related user token. var sessionId = Kernel32.WTSGetActiveConsoleSessionId(); var userTokenPtr = new IntPtr(); if (!WtsApi32.WTSQueryUserToken(sessionId, out userTokenPtr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Duplicate the user token so that it can be used to create a process. var duplicateUserTokenPtr = new IntPtr(); if (!AdvApi32.DuplicateTokenEx(userTokenPtr, AdvApi32.MAXIMUM_ALLOWED, null, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out duplicateUserTokenPtr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Create an environment block for the interactive process. var environmentPtr = new IntPtr(); if (!UserEnv.CreateEnvironmentBlock(out environmentPtr, duplicateUserTokenPtr, false)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Create the process under the target user’s context. var processFlags = CREATE_PROCESS_FLAGS.NORMAL_PRIORITY_CLASS | CREATE_PROCESS_FLAGS.CREATE_NEW_CONSOLE | CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT; var processInfo = new PROCESS_INFORMATION(); var startupInfo = new STARTUPINFO(); startupInfo.cb = Marshal.SizeOf(startupInfo); if (!AdvApi32.CreateProcessAsUser ( duplicateUserTokenPtr, process.StartInfo.FileName, process.StartInfo.Arguments, null, null, false, processFlags, environmentPtr, null, ref startupInfo, out processInfo )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Free used resources. Kernel32.CloseHandle(processInfo.hProcess); Kernel32.CloseHandle(processInfo.hThread); if (userTokenPtr != null) { Kernel32.CloseHandle(userTokenPtr); } if (duplicateUserTokenPtr != null) { Kernel32.CloseHandle(duplicateUserTokenPtr); } if (environmentPtr != null) { UserEnv.DestroyEnvironmentBlock(environmentPtr); } }