public ActionResult Index(SearchTermsModel search, int page = 1) { // Return all Terms // If not a post-back (i.e. initial load) set the searchModel to session if (Request.Form.Count <= 0) { if (search.IsEmpty() && Session["SearchTermsModel"] != null) { search = (SearchTermsModel)Session["SearchTermsModel"]; } } var helper = new TermHelper(); var model = helper.GetTermList(search, search.ParsePage(page)); Session["SearchTermsModel"] = search; //var term = context.Terms.Count() > 0 ? context.Terms.FirstOrDefault(x => x.IsCurrentTerm) : null; //if (term != null) //{ // helper.UpdateStudentsOldDebt(term); //} //else //{ // return View("New", GetTermModel(null)); //} //(search); return(View(model)); }
void Start() { try { Logger.log.Info("Building the gates..."); InitializeComponent(); // For some reason, VS is firing an exceptionn when trying to do this in XAML... this.WindowStartupLocation = WindowStartupLocation.CenterScreen; // Give the NavigationHelper access to the views. Navigation.MainFrame = MainFrame; Navigation.MainWindowInstance = this; // Load the Password_Blacklist into appdata. IOPathHelper.CreateDirectory(IOPathHelper.GetListsDirectory()); if (!File.Exists(IOPathHelper.GetPasswordBlackListFile())) { File.Copy(IOPathHelper.GetAppLocation() + $"\\{TermHelper.GetPasswordBlackListName()}", IOPathHelper.GetPasswordBlackListFile()); Logger.log.Info("Default-Settings have been written!"); } Logger.log.Info("Gates have been built but remain closed."); Testing(); } catch (Exception ex) { ex.SetUserMessage($"A problem occured while trying to build Sen's Fortress. Make sure the program has access to write and read files on and from your harddrive."); Logger.log.Error($"Error while trying to load MainWindow :{ex}"); Communication.InformUserAboutError(ex); } }
private TermHelper GetHelper(int TermId) { TermHelper helper = new TermHelper(TermId); helper.ServiceUserId = GetUserId(); return(helper); }
private TermHelper GetHelper(Term Term) { var helper = new TermHelper(Term); helper.ServiceUserId = GetUserId(); return(helper); }
/// <summary> /// Validates the masterkey by decrypting the given fortress and flushing the memory afterwards. /// </summary> /// <param name="fortressFullPath"></param> /// <param name="fortressName"></param> /// <param name="password"></param> internal void ValidateMasterKey(string fortressFullPath, string fortressName, string password) { try { Logger.log.Info($"Start validating the masterkey of fortress {fortressFullPath}..."); var aesHelper = new AesHelper(); // =========================================================== Unzip the fortress - Read salt var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath); using (unzippedFortress) { var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding(); var saltEntry = unzippedFortress.GetEntry(entryOfSalt); var saltBytes = new byte[32]; using (var stream = saltEntry.Open()) { saltBytes = ByteHelper.ReadBytesOfStream(stream); } Logger.log.Debug("Unzipped fortress - Salt bytes read."); // =========================================================== Create masterkey var hashedKey = aesHelper.CreateKey(password, 256, saltBytes); password = string.Empty; // Delete the password in plaintext from RAM var masterKey = new Masterkey(hashedKey); Logger.log.Debug("Masterkey created."); // =========================================================== Decrypt database var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding(); var databaseEntry = unzippedFortress.GetEntry(entryOfDatabase); var aesAlg = new AesAlgorithm(); using (var stream = databaseEntry.Open()) { var dbBytes = ByteHelper.ReadBytesOfStream(stream); var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes); Logger.log.Info($"Validated {TermHelper.GetDatabaseTerm()}"); decryptedDb = null; } } } catch (Exception ex) { ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
/// <summary> /// Adds an external fortress to the FotressListConfig file. /// </summary> private void LinkExternalFortress() { try { // Open a file dialog var openFileDialog = new OpenFileDialog(); openFileDialog.Filter = $"Fortress (*{TermHelper.GetZippedFileEnding()}) | *{TermHelper.GetZippedFileEnding()}"; openFileDialog.ShowDialog(); if (openFileDialog.FileNames.Count() == 0) { return; } if (File.Exists(IOPathHelper.GetLinkedFortressListFile())) { var linkedFortressesFile = File.ReadAllLines(IOPathHelper.GetLinkedFortressListFile()).ToList(); foreach (var path in openFileDialog.FileNames) { if (linkedFortressesFile.Contains(path)) { Communication.InformUser("You already added this fortress."); return; } linkedFortressesFile.Add(path); } File.WriteAllLines(IOPathHelper.GetLinkedFortressListFile(), linkedFortressesFile); } // If the linkedFortressesFile doesn't exist - write it. else { IOPathHelper.CreateDirectory(IOPathHelper.GetConfigsDirectory()); File.WriteAllLines(IOPathHelper.GetLinkedFortressListFile(), openFileDialog.FileNames); } Logger.log.Info($"Linked external fortress: {openFileDialog.FileName}."); LoadFortresses(); } catch (Exception ex) { Logger.log.Error($"Error while linking a fortress: {ex}"); ex.SetUserMessage($"Couldn't add fortress - An error occured while trying to link it. Make sure the selected file ends with {TermHelper.GetZippedFileEnding()} or try to restart the program."); Communication.InformUserAboutError(ex); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest request, [CosmosDB(ConnectionStringSetting = "DBConnectionString")] IDocumentClient client, ILogger log) { log.LogInformation("TokenDashboardFunction - Completed"); DateTime date; if (!DateTime.TryParseExact(request.Query["date"], "dd-MM-yyyy", null, DateTimeStyles.None, out date)) { return(new BadRequestObjectResult("Input error : Please provide query string 'date' in 'dd-MM-yyyy' format.")); } Uri tokenCollectUri = UriFactory.CreateDocumentCollectionUri("TokenManagerDB", "Token"); var options = new FeedOptions { EnableCrossPartitionQuery = true }; List <TokenDashboardData> dashboardData = new List <TokenDashboardData>(); IDocumentQuery <Token> queryRes = client.CreateDocumentQuery <Token>(tokenCollectUri, options) .OrderBy(token => token.TokenNo) .AsDocumentQuery(); if (queryRes.HasMoreResults) { dashboardData = queryRes.ExecuteNextAsync().Result .Where(token => token.CreatedDate.Date == date.Date) .Select(x => new TokenDashboardData() { TokenNo = x.TokenNo, Service = TermHelper.GetEnumeValue(x.TransactionType.ToString(), typeof(TransactionTypeEnume)), Status = TermHelper.GetEnumeValue(x.Status.ToString(), typeof(TokenStatusEnume)), Action = TermHelper.GetAction(x.Status.ToString()) }).ToList(); } log.LogInformation("TokenDashboardFunction - Completed"); return(new OkObjectResult(dashboardData.OrderBy(x => x.TokenNo))); }
public ClassicalConcept(CompoundAndTermContext compoundAndTermContext, TermOrCompoundTermOrVariableReferer term, BagBuilder bagBuilder, ClassicalBudgetValue budget, Memory memory) : base(budget) { this.memory = memory; this.term = term; tasks = bagBuilder.createForConcept_tasksBag(); taskLinks = bagBuilder.createForConcept_taskLinksBag(); termLinks = bagBuilder.createForConcept_termLinksBag(); { // calculate term links bool isCompoundTerm = !term.isAtomic && !term.isVariable; if (isCompoundTerm) { // TODO< decide if it is COMPOUND_STATEMENT or COMPOUND > // https://github.com/opennars/opennars/blob/4515f1d8e191a1f097859decc65153287d5979c5/nars_core/nars/language/Terms.java#L470; ClassicalTermLink.EnumType type = ClassicalTermLink.EnumType.COMPOUND; this.termLinkTemplates = TermHelper.prepareComponentLinks(compoundAndTermContext, term, type); } } }
/// <summary> /// Stores a serializible model into the datacache /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> internal void StoreOne(ModelBase model, bool isByteModel = false, ByteModel byteModel = null) { CheckDatacache(); // If its a normal ModelBase storing. if (!isByteModel) { var ds = new DataContractSerializer(model.GetType()); var settings = new XmlWriterSettings { Indent = true }; var currentSaveLocation = Path.Combine(_databasePath, TermHelper.GetDatabaseTerm(), model.GetType().Name); // Always check if a directory exists. If not, create it. IOPathHelper.CreateDirectory(currentSaveLocation); using (var sww = new StringWriter()) { using (var w = XmlWriter.Create(Path.Combine(currentSaveLocation, $"{model.Id}.xml"), settings)) { ds.WriteObject(w, model); } } } else if (isByteModel) // If it's a byteModel { var currentSaveLocation = Path.Combine(_databasePath, TermHelper.GetDatabaseTerm(), byteModel.GetType().Name); // It's important to write the bytes decrypted since MemProtection works with the localUser. So the data would be bound to this pc and user. var decryptedValue = CryptMemoryProtection.DecryptInMemoryData(byteModel.EncryptedValue); // Always check if a directory exists. If not, create it. IOPathHelper.CreateDirectory(currentSaveLocation); // Write the Value of byteModels into a file with the foreignKey as the name. File.WriteAllBytes($"{currentSaveLocation}\\{byteModel.ForeignKey}", decryptedValue); decryptedValue = null; } }
/// <summary> /// Fetch all terms from term set /// Required query termsstore guid, termgroup and term set. /// /// GET /// /api/termstore/terms?termstore=244732abfd89492bab7a195786b2cdc7&termgroup=AE-SPOR /// </summary> /// <param name=""termstore""></param> /// <returns></returns> public async Task <IActionResult> Terms([FromQuery(Name = "termstore")] string _termstore, [FromQuery(Name = "termgroup")] string _termgroup) { using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(_baseurl, _username, _password)) try { cc.RequestTimeout = -1; List <TermModel> listTerms = new List <TermModel>(); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc); var termStores = taxonomySession.TermStores; TermStore termStore = termStores.GetById(new Guid(_termstore)); var termGroups = termStore.Groups; var termGroup = termGroups.GetByName(_termgroup); var termSets = termGroup.TermSets; cc.Load(termGroup, group => group.Id, group => group.Name, group => group.TermSets.Include( set => set.Name, set => set.Id, set => set.Terms.Include( term => term.Id, term => term.Name, term => term.Description, term => term.Labels, term => term.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.Labels, term => term.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.Labels, term => term.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.Labels, term => term.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.Labels, term => term.Terms.Include( term => term.Name, term => term.Description, term => term.Id, term => term.Labels ) ) ) ) ) ) ) ); await cc.ExecuteQueryAsync(); for (int i = 0; i < termSets.Count; i++) { TermSet termSet = termSets[i]; var terms = termSet.Terms; foreach (var Aterm in terms) { listTerms.Add(TermHelper.Term(Aterm)); TermCollection BTerms = Aterm.Terms; if (BTerms.Count > 0) { foreach (var BTerm in BTerms) { listTerms.Add(TermHelper.Term(BTerm)); TermCollection CTerms = BTerm.Terms; if (CTerms.Count > 0) { foreach (var CTerm in CTerms) { listTerms.Add(TermHelper.Term(CTerm)); TermCollection DTerms = CTerm.Terms; if (DTerms.Count > 0) { foreach (var DTerm in DTerms) { listTerms.Add(TermHelper.Term(DTerm)); TermCollection ETerms = DTerm.Terms; if (ETerms.Count > 0) { foreach (var ETerm in ETerms) { listTerms.Add(TermHelper.Term(ETerm)); TermCollection FTerms = ETerm.Terms; if (FTerms.Count > 0) { foreach (var FTerm in FTerms) { listTerms.Add(TermHelper.Term(FTerm)); } } } } } } } } } } } } return(new OkObjectResult(listTerms)); } catch (System.Exception) { throw; } }
/// <summary> /// Do NOT use this unless a salt is stored in a single file. /// </summary> internal void StoreSalt(string path, byte[] salt) { CheckDatacache(); File.WriteAllBytes(Path.Combine(path, $"salt{TermHelper.GetTextFileEnding()}"), salt); }
/// <summary> /// Opens a <see cref="Fortress"/> and loads the database. /// </summary> public void BuildFortress(string fortressFullPath, string fortressName, string password) { try { Logger.log.Info($"Start opening the fortress {fortressFullPath}..."); var aesHelper = new AesHelper(); // =========================================================== Unzip the fortress - Read salt var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath); using (unzippedFortress) { var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding(); var saltEntry = unzippedFortress.GetEntry(entryOfSalt); var saltBytes = new byte[32]; using (var stream = saltEntry.Open()) { saltBytes = ByteHelper.ReadBytesOfStream(stream); } CurrentFortressData.Salt = saltBytes; Logger.log.Debug("Unzipped fortress - Salt bytes read."); // =========================================================== Create masterkey var hashedKey = aesHelper.CreateKey(password, 256, saltBytes); password = string.Empty; // Delete the password in plaintext from RAM var masterKey = new Masterkey(hashedKey); hashedKey = null; // Hash also Logger.log.Debug("Masterkey created."); // =========================================================== Decrypt database var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding(); var databaseEntry = unzippedFortress.GetEntry(entryOfDatabase); var aesAlg = new AesAlgorithm(); using (var stream = databaseEntry.Open()) { var dbBytes = ByteHelper.ReadBytesOfStream(stream); var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes); Logger.log.Info($"Decrypted {TermHelper.GetDatabaseTerm()}"); // =========================================================== Unzip database // We distinguish between sensible data and normal data. We put the sensible data into the secureDatacache. var unzippedByteEntriesOfDb = ZipHelper.GetEntriesFromZipArchive(decryptedDb); // These are the entries in byte arrays decryptedDb = null; // Add to secureDC. foreach (var sensibleBytes in unzippedByteEntriesOfDb.Item2.Item2.ToList()) // ToList() otherwise the iterations throws exception { AddToSecureMemoryDC(unzippedByteEntriesOfDb.Item2.Item1.Pop(), unzippedByteEntriesOfDb.Item2.Item2.Pop()); } foreach (var bytes in unzippedByteEntriesOfDb.Item1.ToList()) // Add not sensible data to the "unsecure" DC. { AddToUnsecureMemoryDC(BuildModelsOutOfBytes <ModelBase>(unzippedByteEntriesOfDb.Item1.Pop())); } unzippedByteEntriesOfDb = null; } // Track the security parameters for scans later. SecurityParameterProvider.Instance.UpdateHash(nameof(Fortress), fortressFullPath); } } catch (Exception ex) { ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
/// <summary> /// Creates a new <see cref="Fortress"/> with a <see cref="MasterKey"/> and saves it encrypted. /// </summary> internal void WriteFortress(Fortress fortress, bool overwrite = false) { try { Logger.log.Info("Starting to write a fortress..."); var databasePath = Path.Combine(fortress.FullPath, TermHelper.GetDatabaseTerm()); // =========================================================== Create the root directory IOPathHelper.CreateDirectory(fortress.FullPath); Logger.log.Debug($"Created outer walls {fortress.FullPath}."); // =========================================================== Create the sub directories for the database IOPathHelper.CreateDirectory(databasePath); Logger.log.Debug($"Created the {TermHelper.GetDatabaseTerm()}"); // =========================================================== Create the file which holds the salt to unlock the database StoreSalt(fortress.FullPath, fortress.Salt); Logger.log.Debug("Stored salt"); // =========================================================== Store the user Input and initial data in the database foreach (var modelList in _unsecureDatacache.Values) // UnsecureDatacache { foreach (var model in modelList) { StoreOne(model); } } foreach (var pair in _secureDatacache) { // We filter: Only if the sensible data has a parent we want to save it. Otherwise the parent has been deleted, // which makes the sensible counterpart useless. if (_unsecureDatacache.Values.Any(l => l.Any(m => m.Id == pair.Key))) { var byteModel = new ByteModel(pair.Key, pair.Value); StoreOne(null, true, byteModel); } } Logger.log.Debug("Stored fortress information."); // =========================================================== Zip only the database ZipHelper.ZipSavedArchives(databasePath, $"{databasePath}{TermHelper.GetZippedFileEnding()}"); Directory.Delete(databasePath, true); Logger.log.Debug($"{TermHelper.GetDatabaseTerm()} has been zipped."); // =========================================================== Encrypt the database var aesAlg = new AesAlgorithm(); // Read all bytes from the database directory var data = File.ReadAllBytes($"{databasePath}{TermHelper.GetZippedFileEnding()}"); // Encrypt it var encryptedData = aesAlg.Encrypt(data, fortress.MasterKey.Value, fortress.Salt); // Write the encrypted file File.WriteAllBytes($"{databasePath}{TermHelper.GetDatabaseEnding()}", encryptedData); // Delete the zip File.Delete($"{databasePath}{TermHelper.GetZippedFileEnding()}"); Logger.log.Debug($"Encrypted {TermHelper.GetDatabaseTerm()}"); // =========================================================== Zip the whole fortress if (overwrite) { File.Delete($"{fortress.FullPath}{TermHelper.GetZippedFileEnding()}"); } ZipHelper.ZipSavedArchives(fortress.FullPath, $"{fortress.FullPath}{TermHelper.GetZippedFileEnding()}"); Directory.Delete(fortress.FullPath, true); Logger.log.Debug("Fortress has been zipped."); Logger.log.Info("Fortress has been sucessfully written!"); } catch (Exception ex) { // Delete all changes that have been made to this point. We do not want half-built fortresses. if (Directory.Exists(fortress.FullPath)) { Directory.Delete(fortress.FullPath, true); } if (File.Exists(Path.Combine(fortress.FullPath, TermHelper.GetZippedFileEnding()))) { File.Delete(fortress.FullPath + TermHelper.GetZippedFileEnding()); } ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage()); throw ex; } }
private async void Save_Button_Click(object sender, RoutedEventArgs e) { try { await Task.Run(() => { Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "Validating your rights..."); // Validate the key first. if (DataAccessService.Instance.ValidateMasterkey(masterPasswordBox.Password)) { var aesHelper = new AesHelper(); var hashedKey = aesHelper.CreateKey(masterPasswordBox.Password, 256, CurrentFortressData.Salt); var secureMasterkey = new Masterkey(hashedKey); hashedKey = null; Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "You have the correct keys my friend."); IOPathHelper.CreateDirectory(IOPathHelper.GetBackedUpFortressDirectory()); // Make sure the directory exists. // Backup fortress Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "Backup-ing your fortress..."); DataAccessService.Instance.BackupFortress( System.IO.Path.Combine(IOPathHelper.GetBackedUpFortressDirectory(), $"(Backup){CurrentFortressData.FortressName}{TermHelper.GetZippedFileEnding()}")); Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "Fortress backed up. Proceeding to save the fortress..."); // Now save the fortress. DataAccessService.Instance.SaveFortress(secureMasterkey); Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "Fortress saved successfully."); // Backup the fortress again with the newly saved changes. DataAccessService.Instance.BackupFortress( System.IO.Path.Combine(IOPathHelper.GetBackedUpFortressDirectory(), $"(Backup){CurrentFortressData.FortressName}{TermHelper.GetZippedFileEnding()}")); Thread.Sleep(1000); // Make the user see the result for a second. Application.Current.Dispatcher.Invoke(() => DialogResult = true); } else { Application.Current.Dispatcher.Invoke(() => InformationPanel_Textblock.Text = "The mission could not be executed."); return; } }); } catch (Exception ex) { Logger.log.Error(ex); InformationPanel_Textblock.Text = "The mission could not be executed."; return; } finally { masterPasswordBox.Password = string.Empty; // Delete the password } }
/// <summary> /// Loads all fortresses: Default and linked. /// </summary> public void LoadFortresses() { try { // If the fortress folder doesn't exist, a fortress hasn't been created into the default location if (!Directory.Exists(IOPathHelper.GetDefaultFortressDirectory()) && !File.Exists(IOPathHelper.GetLinkedFortressListFile())) { return; } var allFortresses = new List <string>(); // First get all fortresses in the default location var defaultFortresses = Directory.GetFiles(IOPathHelper.GetDefaultFortressDirectory()).Where(f => f.EndsWith(TermHelper.GetZippedFileEnding())).ToList(); allFortresses.AddRange(defaultFortresses); // Now look for externally added fortress in the fortress config if (File.Exists(IOPathHelper.GetLinkedFortressListFile())) { var linkedFortresses = File.ReadAllLines(IOPathHelper.GetLinkedFortressListFile()).ToList(); var emptyPaths = new List <string>(); foreach (var path in linkedFortresses) { // If the file exists, we add it to the UI. if (File.Exists(path)) { allFortresses.Add(path); } // If the given path does not exist anymore, because the fortress got moved, delete it. else { emptyPaths.Add(path); } } // When empty paths have been found, delete them and tell the User. if (emptyPaths.Count > 0) { foreach (var path in emptyPaths) { linkedFortresses.Remove(path); } File.WriteAllLines(IOPathHelper.GetLinkedFortressListFile(), linkedFortresses); Communication.InformUser($"Old or corrupted paths have been found - they were de-linked from the fortress list."); } } Fortresses.Clear(); foreach (var fortress in allFortresses) { // If the files does not have the default database ending, skip it. if (!fortress.EndsWith(TermHelper.GetZippedFileEnding())) { break; } var created = File.GetCreationTime(fortress); var modified = File.GetLastWriteTime(fortress); var fortressVm = new FortressViewModel(fortress, created, modified, this); if (!fortress.Contains(IOPathHelper.GetDefaultFortressDirectory())) { fortressVm.IsDefaultLocated = false; } Fortresses.Add(fortressVm); } } catch (Exception ex) { Logger.log.Error($"Error while loading the fortress list: {ex}"); ex.SetUserMessage("An error occured while trying to load all known fortresses. If the fortress has been moved, try to select it again or restart the program."); Communication.InformUserAboutError(ex); } }
/// <summary> /// /// </summary> /// <param name="docs"></param> /// <returns></returns> public async Task <IActionResult> Test([FromBody] DocumentModel[] docs) { if (docs.Length == 0) { return(new NoContentResult()); } SMB2Client client = new SMB2Client(); string site = docs[0].site; string url = _baseurl + "sites/" + site; string listname = docs[0].list; Guid listGuid = new Guid(listname); using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(url, _username, _password)) try { ///SMBCredential SMBCredential = new SMBCredential(){ /// username = Environment.GetEnvironmentVariable("smb_username"), /// password = Environment.GetEnvironmentVariable("smb_password"), /// domain = Environment.GetEnvironmentVariable("domain"), /// ipaddr = Environment.GetEnvironmentVariable("ipaddr"), /// share = Environment.GetEnvironmentVariable("share"), ///}; /// ///var serverAddress = System.Net.IPAddress.Parse(SMBCredential.ipaddr); ///bool success = client.Connect(serverAddress, SMBTransportType.DirectTCPTransport); /// ///NTStatus nts = client.Login(SMBCredential.domain, SMBCredential.username, SMBCredential.password); ///ISMBFileStore fileStore = client.TreeConnect(SMBCredential.share, out nts); List list = cc.Web.Lists.GetById(listGuid); var fieldcollection = list.Fields; cc.Load(fieldcollection); cc.ExecuteQuery(); var cquery = new CamlQuery(); cquery.ViewXml = string.Format(@"<View> <Query> <Where> <Eq><FieldRef Name='Title' /> <Value Type='Text'>{0}</Value></Eq> </Where> </Query> </View>", "dummy.pdf"); var listitems = list.GetItems(cquery); cc.Load(listitems); cc.ExecuteQuery(); ListItem item = listitems[0]; var clientRuntimeContext = item.Context; string[] SPORDocPropertyNo = { "4223-7/1", "4223-7/3", "4223-7/4", "4223-7/5" }; foreach (var fieldObj in fieldcollection) { if (fieldObj.InternalName.Equals("SPORDocPropertyNo")) { var taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(fieldObj); Guid _id = taxKeywordField.TermSetId; List <string> ListTermString = new List <string>(); for (int i = 0; i < SPORDocPropertyNo.Length; i++) { string _termID = TermHelper.GetTermIdByName(cc, SPORDocPropertyNo[i], _id); ListTermString.Add(string.Format("-1;#{0}{1}{2}", SPORDocPropertyNo[i], "|", _termID)); } string tax = string.Join(";#", ListTermString); Console.WriteLine(tax); taxKeywordField.SetFieldValueByValueCollection(item, new TaxonomyFieldValueCollection(cc, tax, taxKeywordField)); taxKeywordField.Update(); break; } } item.Update(); await cc.ExecuteQueryAsync(); } catch (System.Exception) { throw; } finally { //client.Logoff(); //client.Disconnect(); } return(new NoContentResult()); }
public async Task <IActionResult> td([FromBody] DocumentModel[] docs) { if (docs.Length == 0) { return(new NoContentResult()); } SMB2Client client = new SMB2Client(); string site = docs[0].site; string url = _baseurl + "sites/" + site; string listname = docs[0].list; Guid listGuid = new Guid(listname); using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(url, _username, _password)) try { SMBCredential SMBCredential = new SMBCredential() { username = Environment.GetEnvironmentVariable("smb_username"), password = Environment.GetEnvironmentVariable("smb_password"), domain = Environment.GetEnvironmentVariable("domain"), ipaddr = Environment.GetEnvironmentVariable("ipaddr"), share = Environment.GetEnvironmentVariable("share"), }; var serverAddress = System.Net.IPAddress.Parse(SMBCredential.ipaddr); bool success = client.Connect(serverAddress, SMBTransportType.DirectTCPTransport); NTStatus nts = client.Login(SMBCredential.domain, SMBCredential.username, SMBCredential.password); ISMBFileStore fileStore = client.TreeConnect(SMBCredential.share, out nts); List list = cc.Web.Lists.GetById(listGuid); List <Metadata> fields = SharePointHelper.GetFields(cc, list); //List list = cc.Web.Lists.GetByTitle(listname); for (int i = 0; i < docs.Length; i++) { string filename = docs[i].filename; string file_url = docs[i].file_url; var inputFields = docs[i].fields; var taxFields = docs[i].taxFields; FileCreationInformation newFile = SharePointHelper.GetFileCreationInformation(file_url, filename, SMBCredential, client, nts, fileStore); ///FileCreationInformation newFile = SharePointHelper.GetFileCreationInformation(file_url, filename); if (newFile == null) { _logger.LogError("Failed to upload. Skip: " + filename); continue; } File uploadFile; if (docs[i].foldername == null) { uploadFile = list.RootFolder.Files.Add(newFile); } else { string foldername = docs[i].foldername; string sitecontent = docs[i].sitecontent; //Folder folder = list.RootFolder.Folders.GetByUrl(foldername); Folder folder = SharePointHelper.GetFolder(cc, list, foldername); if (folder == null && taxFields != null) { folder = SharePointHelper.CreateDocumentSetWithTaxonomy(cc, list, sitecontent, foldername, inputFields, fields, taxFields); } else if (folder == null) { folder = SharePointHelper.CreateFolder(cc, list, sitecontent, foldername, inputFields, fields); } //cc.ExecuteQuery(); uploadFile = folder.Files.Add(newFile); } _logger.LogInformation("Upload file: " + newFile.Url); ListItem item = uploadFile.ListItemAllFields; if (taxFields != null) { var clientRuntimeContext = item.Context; for (int t = 0; t < taxFields.Count; t++) { var inputField = taxFields.ElementAt(t); var fieldValue = inputField.Value; var field = list.Fields.GetByInternalNameOrTitle(inputField.Key); cc.Load(field); cc.ExecuteQuery(); var taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(field); Guid _id = taxKeywordField.TermSetId; string _termID = TermHelper.GetTermIdByName(cc, fieldValue, _id); TaxonomyFieldValue termValue = new TaxonomyFieldValue() { Label = fieldValue.ToString(), TermGuid = _termID, }; taxKeywordField.SetFieldValueByValue(item, termValue); taxKeywordField.Update(); } } DateTime dtMin = new DateTime(1900, 1, 1); Regex regex = new Regex(@"~t.*"); if (inputFields != null) { foreach (KeyValuePair <string, string> inputField in inputFields) { if (inputField.Value == null || inputField.Value == "") { continue; } string fieldValue = inputField.Value; Match match = regex.Match(fieldValue); Metadata field = fields.Find(x => x.InternalName.Equals(inputField.Key)); if (field.TypeAsString.Equals("User")) { int uid = SharePointHelper.GetUserId(cc, fieldValue); item[inputField.Key] = new FieldUserValue { LookupId = uid }; } //endre hard koding else if (inputField.Key.Equals("Modified_x0020_By") || inputField.Key.Equals("Created_x0020_By") || inputField.Key.Equals("Dokumentansvarlig")) { StringBuilder sb = new StringBuilder("i:0#.f|membership|"); sb.Append(fieldValue); item[inputField.Key] = sb; } else if (match.Success) { fieldValue = fieldValue.Replace("~t", ""); if (DateTime.TryParse(fieldValue, out DateTime dt)) { if (dtMin <= dt) { item[inputField.Key] = dt; _logger.LogInformation("Set field " + inputField.Key + "to " + dt); } else { continue; } } } else { item[inputField.Key] = fieldValue; _logger.LogInformation("Set " + inputField.Key + " to " + fieldValue); } } item.Update(); } try { await cc.ExecuteQueryAsync(); Console.WriteLine("Successfully uploaded " + newFile.Url + " and updated metadata"); } catch (System.Exception e) { _logger.LogError("Failed to update metadata."); Console.WriteLine(e); continue; } } } catch (System.Exception) { throw; } finally { client.Logoff(); client.Disconnect(); } return(new NoContentResult()); }