c# IndexOf does not exist in current context - c#

I'm trying to use the following and can't wrap my head around why this IndexOf method isn't working.
foreach (string s in regKey.GetSubKeyNames())
{
RegistryKey sub = Registry.LocalMachine.OpenSubKey(string.Format(#"{0}\{1}", _UninstallKey64Bit, s), false);
if (sub.ValueCount > 0)
{
values = sub.GetValueNames();
if (IndexOf(values, "DisplayName") != -1)
{
string name = (sub.GetValue("DisplayName") != null) ? sub.GetValue("DisplayName").ToString() : string.Empty;
if (!string.IsNullOrEmpty(name) && (name.ToLower() == appName.ToLower()))
if (IndexOf(values, "UninstallString") != -1)
{
uninstallValue = (sub.GetValue("UninstallString") != null) ? sub.GetValue("UninstallString").ToString() : string.Empty;
break;
}
}
}
}
Can anyone lend me a hand with this?

Correct syntax is:
if (Array.IndexOf(values, "DisplayName") != -1)

GetValueNames() returns a string array so you probably are looking for:
if (values.Contains("DisplayName"))

Try
if (values.Any(v => v == "DisplayName")) )
{
...
}

Try changing -
if (IndexOf(values, "UninstallString") != -1)
to
if (Array.IndexOf(values, "UninstallString") != -1)

Try this instead of just IndexOf.
Array.IndexOf(values, "DisplayName")

Related

How to overcome foreach loop for list object dynamically

I'm swapping my values in List Object on some conditions and update List Object value.
Currently, what I'm doing is
- Looping on each object through List
- Check If condition is net
- Swap values
public static void SwapMinMaxIfNull<T>(this IEnumerable<T> rows, string reportfor)
{
if (reportfor.Equals("Comparison"))
{
var row = rows as IEnumerable<RiskBoardDataToExport>;
try
{
if (rows.Any())
{
var Tests = row.Where(min => min.MinGaitSpeed == null && min.MaxGaitSpeed != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinGaitSpeed = test.MaxGaitSpeed;
test.MaxGaitSpeed = null;
}
}
// again check for next object
Tests = row.Where(min => min.MinTUGTime == null && min.MaxTUGTime != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinTUGTime = test.MaxTUGTime;
test.MaxTUGTime = null;
}
}
// again check for next object
Tests = row.Where(min => min.MinBergScoreSpeed == null && min.MaxBergScoreSpeed != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinBergScoreSpeed = test.MaxBergScoreSpeed;
test.MaxBergScoreSpeed = null;
}
}
//.. for brevity
}
}
}
Can I do it in better way? I know about PropertyInfo i.e. Can check property name and get value etc, but, not having any hint to get this done.
Thanks
It's not exactly what you're asking for, but you can combine the clauses in your Where statements and then have a few if statements in the body:
public static void SwapMinMaxIfNull(this IEnumerable<RiskBoardDataToExport> rows,
string reportfor)
{
if (rows = null) return;
if (reportfor.Equals("Comparison", StringComparison.OrdinalIgnoreCase))
{
foreach (var row in rows.Where(r =>
(r.MinGaitSpeed == null && r.MaxGaitSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null)))
{
if (row.MinGaitSpeed == null)
{
row.MinGaitSpeed = row.MaxGaitSpeed;
row.MaxGaitSpeed = null;
}
if (row.MinTUGTime == null)
{
row.MinTUGTime = row.MaxTUGTime;
row.MaxTUGTime = null;
}
if (row.MinBergScoreSpeed == null)
{
row.MinBergScoreSpeed = row.MaxBergScoreSpeed;
row.MaxBergScoreSpeed = null;
}
}
}
}
As this is an operation where order of the items in the list does not matter, you can easily speed this up by parallelization (you can read up on that here).
So, what you should do, is handle this foreach loop in a parallel way and combine it with Rufus L's optimized code for the fastest result.
var rows = rows.Where(r =>
(r.MinGaitSpeed == null && r.MaxGaitSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null))
Parallel.ForEach(rows, (row) => {
{
if (row.MinGaitSpeed == null)
{
row.MinGaitSpeed = row.MaxGaitSpeed;
row.MaxGaitSpeed = null;
}
if (row.MinTUGTime == null)
{
row.MinTUGTime = row.MaxTUGTime;
row.MaxTUGTime = null;
}
if (row.MinBergScoreSpeed == null)
{
row.MinBergScoreSpeed = row.MaxBergScoreSpeed;
row.MaxBergScoreSpeed = null;
}
}
Note that this requires the System.Threading.Tasks namespace, that's where the Parallel class is.

Refactor if statements

What is a best way for refactor "if" statements?
My method fragment:
if (code == SystemCode.Enum1.ToString())
{
user.IsEnum1 = result != null;
}
if (code == SystemCode.Enum2.ToString())
{
user.IsEnum2 = result != null;
}
if (code == SystemCode.Enum3.ToString())
{
user.IsEnum3 = result != null;
}
I would try this approach:
enum MyEnum
{
Enum1,
Enum2,
Enum3
}
class User
{
Dictionary<MyEnum, bool> enumList;
public void InitEnumList()
{
enumList = new Dictionary<MyEnum, bool>();
foreach (var item in Enum.GetValues(typeof(MyEnum)))
{
//Set the default key-value pairs
enumList.Add((MyEnum)item, false);
}
}
}
Switch statement is one of the good option for avoiding multiple if statements
Try this:
if (( !(code != ((int)SystemCode.Enum1).ToString() || (user.IsEnum1 = result != null).ToString().Length > 0))
|| !(code != ((int)SystemCode.Enum2).ToString() || (user.IsEnum2 = result != null).ToString().Length > 0)
|| !(code != ((int)SystemCode.Enum3).ToString() || (user.IsEnum3 = result != null).ToString().Length > 0))
{
return;
}
I know it looks complex but isn't that what you wanted. Let me know if you have any queries.

Due to LINQ Retrieving of Record data's i have this error: NullReferenceException was unhandled by user code

private void getUserLoginDepartment(string AccessID, string UserPROFid)
{
try
{
DBWPAccountRecordsDataContext DBACCOUNT = new DBWPAccountRecordsDataContext();
var query = (from i in DBACCOUNT.WP_UserAccessPorts
join
z in DBACCOUNT.WP_Departments on i.AccessPortID equals z.Dept_ID
where i.AccessPortID == AccessID && i.ProfileUser_ID == UserPROFid
select new
{
PORT1 = i.AccessPoint1,
PORT2 = i.AccessPoint2,
PORT3 = i.AccessPoint3,
PORT4 = i.AccessPoint4,
DEPT = z.Dept_DESC,
DEPTPORT = z.Dept_PortNo
}).FirstOrDefault();
if (query.PORT1.ToString() != null || query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
else { Session["Port1"] = ""; }
if (query.PORT2.ToString() != null || query.PORT2.ToString() != string.Empty)
{ Session["Port2"] = query.PORT2; }
else { Session["Port2"] = ""; }
if (query.PORT3.ToString() != null || query.PORT3.ToString() != string.Empty)
{ Session["Port3"] = query.PORT3; }
else { Session["Port3"] = ""; }
if (query.PORT4.ToString() != null || query.PORT4.ToString() != string.Empty)
{ Session["Port4"] = query.PORT4; }
else { Session["Port4"] = ""; }
}
finally
{
}
}
The Error occures when i reach break point 1st IF Statement the record on my database shows that its not empty which its value is "WebAdmin" but then suppost to be it should pick it up and store it to the Session["PORT1"] that i have made is there something i missed or i'm doing it wrong on my linq Query. NOTE:*This is an ASP.NET C# Application
EDIT 10/2/2013 0420PM:
It's still an Error After using that method sir.
1) you should check query for null when you use FirstOrDefault
2) you need to check each PORTX for null
3) use string.IsNullOrEmpty( ) to check if the string of PORTX is null
var query = ( ... ).FirstOrDefault( );
if( query != null )
{
if( query.PORT1 != null && !string.IsNullOrEmpty( query.PORT1.ToString( ) ) )
{
}
else { ... }
}
You have to check query.PORT1 for null before calling ToString on it, you can use String.IsNullOrEmpty to check both conditions. Before checking query.PORT1 you need to check if query is null or not. You also need to use && instead of or operator as || will cause the right side of or operator to be evaluated if left is false and on right side calling ToString on null will again through exception.
if (query != null && query.PORT1 != null && query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
Using IsNullOrEmpty
if(query != null && !String.IsNullOrEmpty(query.PORT1))
{
Session["Port1"] = query.PORT1;
}

Variables within lambda/LINQ

is there a way for bellow lambda expression to move the method call ConvertFilterType(filter.FilterTypeId) into a variable so it is not called repeatedly for every condition ?
This if statement is making sure collection consist of all required filters.
if (run.Filters.All(
filter => (ConvertFilterType(filter.FilterTypeId) != FilterType.A)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.B)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.C)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.D)
&& (ConvertFilterType(filter.FilterTypeId) != FilterType.E)))
{
throw new ArgumentException();
}
if (run.Filters.All(
filter => {
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A && t != FilterType.B && t != FilterType.C && t != FilterType.D && t != FilterType.E;
}))
{
throw new ArgumentException();
}
King beat me to it. Although it is not what you asked, I would also recommend that for improved readability, that you create a separate method with a more meaningful name. This chain of logic can obscure the intent of what you are doing. Extracting it into a method would help clarify the method's intent. I would have put this in the comment's to King's post, but don't have the reputation yet.
Here is some sample code, though I don't know what the type of the items in your Filters collection to know what the parameter of the method would need to be.
if (run.Filters.All(filter => { return IsFilterAllowed(filter); } )
{
throw new ArgumentException();
}
private bool IsFilterAllowed(FiltersItemType filter)
{
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A &&
t != FilterType.B &&
t != FilterType.C &&
t != FilterType.D &&
t != FilterType.E;
}
King's answer is the way to go but could you could also do this it seems.
FilterType[] notTheseFilters = new FilterType[] { FilterType.A, FilterType.B...};
bool result = !Filters.Any(f =>
notTheseFilters.Contains(ConvertFilterType(f.FilterTypeId)));
If my logic serves me right, you could also do this
var filterTypesToAvoid = new[]{
FilterType.A,
FilterType.B,
FilterType.C,
FilterType.D,
FilterType.E
};
if (run.Filters.All(
filter => !filterTypesToAvoid.Contains(ConvertFilterType(filter.FilterTypeId))
))
{
throw new ArgumentException();
}
This way there is no need for brackets in the LINQ query.
To extend what brader24 proposed, you could try :
if (run.Filters.All(IsFilterAllowed))
{
throw new ArgumentException();
}
private bool IsFilterAllowed(FiltersItemType filter)
{
FilterType t = ConvertFilterType(filter.FilterTypeId);
return
t != FilterType.A &&
t != FilterType.B &&
t != FilterType.C &&
t != FilterType.D &&
t != FilterType.E;
}

.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

I'm attempting to use Contracts in my .Net 3.5 (C#) project. I found where I had written something like if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) throw new ArgumentException("Required", "s"); at the beginning of methods.
I could keep them there and use legacy contracts. I could change it to Contract.Requires(s!= null && string.IsNullOrEmpty(s.Trim()));. But besides not being very sure about the correctness or performance of the Whitespace part of the condition, those are lame (opinion).
Instead, I tried to encapsulate the condition in a method for use in Contracts. Problem is that I still can't figure out how to describe the Whitespace part declaratively. The static checker finds several issues depending on how I write it.
I'd like to hear comments about the appropriateness of data content checks such as this one for whitespace AS WELL AS a correct definition.
public static class str
{
[Pure]
public static bool IsNullOrWhitespace(string s)
{
Contract.Ensures(s != null || Contract.Result<bool>());
Contract.Ensures((s != null && !Contract.ForAll<char>(s, c => char.IsWhiteSpace(c))) || Contract.Result<bool>());
if (s == null) return true;
for (var i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s, i))
{
Contract.Assume(!Contract.ForAll<char>(s, c => char.IsWhiteSpace(c)));
return false;
}
}
return true;
}
}
This might be sloppy, but my initial experimentation method is here. The Asserts on a, b, and c are failing or are unproven.
static void Test()
{
string a = null;
string b = "";
string c = " ";
string d = "xyz";
string e = " xyz ";
if (!str.IsNullOrWhitespace(a))
{
Contract.Assert(a != null);
a = a.Trim();
}
if (!str.IsNullOrWhitespace(b))
{
Contract.Assert(b != null && b != "");
b = b.Trim();
}
if (!str.IsNullOrWhitespace(c))
{
Contract.Assert(c != null && c != " ");
c = c.Trim();
}
if (!str.IsNullOrWhitespace(d))
{
d = d.Trim();
}
if (!str.IsNullOrWhitespace(e))
{
e = e.Trim();
}
}
Here's the built-in contract from .NET 4:
Contract.Ensures(
(Contract.Result<bool>() && ((str == null) || (str.Length == 0)))
? ((bool) true)
: ((Contract.Result<bool>() || (str == null))
? ((bool) false)
: ((bool) (str.Length > 0)))
, null, "Contract.Result<bool>() && (str == null || str.Length == 0) ||\r\n!Contract.Result<bool>() && str != null && str.Length > 0");
Despite its complexity, you can see that there is no mention of whitespace. I've tried several times, but I can't get something working that will satisfy the static checker.
There appear to be a couple of issues stopping me from writing it, so I've filed some questions on the Code Contracts forum.
My contract was:
Contract.Ensures(Contract.Result<bool>() ==
(s == null || Contract.Exists(s, char.IsWhiteSpace)))

Categories