Properties.Settings.Default.variableName = textboxt.Text - c#

private void Enable(TextBox temp, String system)
{
if (File.Exists(temp.Text))
{
Properties.Settings.Default.system = temp.Text;
}
else
do something here;
}
Basically I'm trying to take a text box with some file path, check if it exists, if exists set the value of the Properties.Settings.Default.system to temp.text.
However I don't know how to use a variable name to reference the existing settings property.
Fairly new to this so any help is appreciated.
Thanks!

Credit to Mike Debela for the answer.... But if ran into a situation where you don't know the system, this code will help prevent some errors.
private void Enable(TextBox Temp, string system)
{
// check that the property even exists
bool propertyExists = Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(p => p.Name == system);
if (propertyExists)
{
Properties.Settings.Default[system] = Temp.Text;
}
else
{
// create a new property
var p = new SettingsProperty(system);
p.PropertyType = typeof(string);
p.DefaultValue = Temp.Text;
Properties.Settings.Default.Properties.Add(p);
}
Properties.Settings.Default.Save();
}

Related

c# NavisWorks ModelItem isReadOnly() always true

I try to add some new property in existing category for selected NavisWorks ModelItem`s
There is not so many example over network, and it base on same COM approach.
However there special method to add property available in API.
Only issue that objects is locked.
Is there any way to unlock it?
using ANA = Autodesk.Navisworks.Api;
...
private void addProperty(string category, string prop, string value)
{
var oDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;
ModelItemCollection selectionModelItems = new ModelItemCollection();
ANA.Application.ActiveDocument.CurrentSelection.SelectedItems.CopyTo(selectionModelItems);
//Clear the current selection
ANA.Application.ActiveDocument.CurrentSelection.Clear();
try
{
foreach (ModelItem m in selectionModelItems)
{
foreach (PropertyCategory p in m.PropertyCategories)
{
if (p.DisplayName != category) continue;
var property = new DataProperty(prop, prop, new VariantData(value));
p.Properties.Add(property);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
result of execution:
Properties and categories which are created by Navisworks are read-only.
You can not add or modify properties or categories which are created by Navisworks.
You can only create or add user-defined properties - using COM.
See:
https://adndevblog.typepad.com/aec/2012/05/create-attributes-and-properties-for-model-objects-using-net-api.html
https://adndevblog.typepad.com/aec/2012/08/addmodifyremove-custom-attribute-using-com-api.html
https://forums.autodesk.com/t5/navisworks-api/navisworks-api-add-user-data-tab/td-p/2916866
Here is a code snippet (copied from xiaodong.liang forum post mentioned above) which shows how to add a user-defined property using COM:
private void addProperty() {
ComApi.InwOpState10 state;
state = ComApiBridge.ComApiBridge.State;
ModelItemCollection modelItemCollectionIn = new ModelItemCollection(Autodesk.Navisworks.Api.Application.ActiveDocument.CurrentSelection.SelectedItems);
ComApi.InwOpSelection comSelectionOut =
ComApiBridge.ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
ComApi.InwSelectionPathsColl oPaths = comSelectionOut.Paths();
ComApi.InwOaPath3 oPath = (ComApi.InwOaPath3) oPaths.Last();
ComApi.InwGUIPropertyNode2 propn = (ComApi.InwGUIPropertyNode2) state.GetGUIPropertyNode(oPath, true);
ComApi.InwOaPropertyVec newPvec = (ComApi.InwOaPropertyVec) state.ObjectFactory(Autodesk.Navisworks.Api.Interop.ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
ComApi.InwOaProperty newP = (ComApi.InwOaProperty) state.ObjectFactory(Autodesk.Navisworks.Api.Interop.ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
newP.name = "LXD_Property_Name";
newP.UserName = "LXD_Property_UserName";
newP.value = "LXD_Property_Value";
newPvec.Properties().Add(newP);
propn.SetUserDefined(0, "LXD_PropertyTab_Name", "LXD_PropertyTab_InteralName", newPvec);
}

Ban a variable from a list with a "ban" list

How can I ban a variable from a list without removing it from that list by adding the variable to a list of "banned" variable?
I wish to be able to type in a string. That string is compared to the file names in a folder. If there is a match, the file is read. If I type this same string again, the file should not be read again. There for I want to have a list of "banned" string that is checked whilst typing to avoid the file to be read again.
I have tried a few ways but not getting there. Below is an example of my last attempt.
What would be the best way?
public class test
{
string scl= "test3";
List <string> lsf,lso;
void Start ()
{
lsf=//file names
new List<string>();
lso=//files open
new List<string>();
lsf.Add("test0");
lsf.Add("test1");
lsf.Add("test2");
lsf.Add("test3");
lsf.Add("test4");
lso.Add("idhtk49fngo");//random string
}
void Update ()
{
if
(
Input.GetKeyDown("a")
)
{
for
(
int i=0;
i<lsf.Count;
i++
)
{
if(lsf[i]==scl)
{
Debug.Log
(i+" is read");
for
(
int j=0;
j<lso.Count;
j++
)
{
//how can i avoid reading
//lsf[3] here the second time
//"a" is pressed (by having "test3"
//added to a "ban" list (lso) )
if(scl!=lso[j])
{
lso.Add(lsf[i]);
}
}
}
}
}
}
Michael’s answer is the way to go here but it can be improved using the more appropriate collection available to keep track of opened files; if you want uniqueness use a set, not a list:
HashSet<string> openedFiles = new HashSet<string>();
public static bool TryFirstRead(
string path,
out string result)
{
if (openedFiles.Add(path))
{
result = File.ReadAllText(path);
return true;
}
result = null;
return false;
}
Also, I’d avoid throwing vexing exceptions. Give the consumer a friendly way to know if the file was read or not, don’t make them end up having to use exceptions as a flow control mechanism.
I didn't understand although if you want to replace a value from another list.
You can use the list index to create a new list with the values which you removed.
String list1 = {"hi", "hello", "World"};
String list2 = {"bye", "goodbye", "World"};
List1[1] = list2[1];
I would suggest such way:
public static List<string> openedFiles = new List<string>();
public static string ReadFileAndAddToOpenedList(string path)
{
if (openedFiles.Contains(path))
throw new Exception("File already opened");
// Instead of throwing exception you could for example just log this or do something else, like:
// Consolle.WriteLine("File already opened");
else
{
openedFiles.Add(path);
return File.ReadAllText(path);
}
}
The idea is - on every file read, add file to list, so you can check every time you try read file, if it was already read (or opened). If it is, throw exception (or do something else). Else read a file.
You could instead of making it a string list use your own class
public class MyFile
{
public string Name;
public bool isOpen;
public MyFile(string name)
{
Name = name;
isOpen = false;
}
}
List<MyFile> lsf = new List<MyFile>()
{
new MyFile("test0"),
new MyFile("test1"),
new MyFile("test2"),
new MyFile("test3"),
new MyFile("test4")
};
Than when you read the file set isOpen to true
MyFile[someIndex].isOpen = true;
and later you can check this
// E.g. skip in a loop
if(MyFile[someIndex]) continue;
You could than also use Linq in order to get a list of only unread files:
var unreadFiles = lsf.Select(f => f.Name).Where(file => !file.isOpen);

Parse.com - if key exists, update

Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}

Error on loading user control

i want to load my own designed User Control to the form but when i drag and place the user Control it produces the Error. Please Kindly refer my Screen Shot and help me to solve this issue.
The error where in code is i mentioned as line no:
private void populateTransfers(bool all)
{
AccountTransfer[] accounts;
//List<ReferenceData._account> headers = ReferenceData.getIndentHeader_account();
if (all)
accounts = accountClient.getAllPendingTransfers();
else
accounts = accountClient.getPendingTransfers(Program.loggedInUser.account.id);//line no:47
if (accounts != null)
{
var query = from a in accounts
select new
{
Id = a.id,
Name=a.name,
Status = a.status,
Date = a.ludt.ToShortDateString()
};
this.gridPendingTransfers.DataSource = query.ToList();
this.gridPendingTransfers.RefreshDataSource();
}
else
{
CexAppUtil.ShowEmptyGrid("No pending transfers", this.gridPendingTransfers);
}
private void initializeData()
{
if (Program.loggedInUser != null && Program.loggedInUser.isAdmin())
{
pendingTransferOptionsPanel.Visible = true;
showAllPendingTransfers.Visible = true;
if (showAllPendingTransfers.Checked) populateTransfers(true);
else populateTransfers(false);
}
else
{
pendingTransferOptionsPanel.Visible = false;
showAllPendingTransfers.Visible = false;
populateTransfers(false);//line no:167
}
}
Please help me to solve this problem.
Thanks-in Advance.
You can debug and find the error in your custom control by starting a new instance of visual studio and attach the debugger to the process of the first instance.
After that you can add your new control and see which object is null.
Are doing some work in constructor? Delete all code from constructor instead of InitilizeComponents(). Then make a new Initilize Method where you copy the code from constructor. This method you call in form.load or sth. Try it out ;) – # Sebi
Thank to every-one.

Get current ClickOnce's application publisher name?

Is it possible to read the publisher name of the currently running ClickOnce application (the one you set at Project Properties -> Publish -> Options -> Publisher name in Visual Studio)?
The reason why I need it is to run another instance of the currently running application as described in this article and pass parameters to it.
Of course I do know my application's publisher name, but if I hard code it and later on I decide to change my publisher's name I will most likely forget to update this piece of code.
Here is another option. Note that it will only get the publisher name for the currently running application, which is all I need.
I'm not sure if this is the safest way to parse the XML.
public static string GetPublisher()
{
XDocument xDocument;
using (MemoryStream memoryStream = new MemoryStream(AppDomain.CurrentDomain.ActivationContext.DeploymentManifestBytes))
using (XmlTextReader xmlTextReader = new XmlTextReader(memoryStream))
{
xDocument = XDocument.Load(xmlTextReader);
}
var description = xDocument.Root.Elements().Where(e => e.Name.LocalName == "description").First();
var publisher = description.Attributes().Where(a => a.Name.LocalName == "publisher").First();
return publisher.Value;
}
You would think this would be trivial, but I don't see anything in the framework that gives you this info.
If you want a hack, you can get the publisher from the registry.
Disclaimer - Code is ugly and untested...
...
var publisher = GetPublisher("My App Name");
...
public static string GetPublisher(string application)
{
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall"))
{
var appKey = key.GetSubKeyNames().FirstOrDefault(x => GetValue(key, x, "DisplayName") == application);
if (appKey == null) { return null; }
return GetValue(key, appKey, "Publisher");
}
}
private static string GetValue(RegistryKey key, string app, string value)
{
using (var subKey = key.OpenSubKey(app))
{
if (!subKey.GetValueNames().Contains(value)) { return null; }
return subKey.GetValue(value).ToString();
}
}
If you find a better solution, please follow-up.
I dont know about ClickOnce, but normally, you can read the assembly-info using the System.Reflection framework:
public string AssemblyCompany
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
Unfortunately, theres no "publisher" custom-attribute, just throwing this out as a possible work-around

Categories

Resources