set control ID using string.concat - asp.net

i've some code in c#, in which there are many lines of code where the ID of a control is set by string.concat. For ex:
private genericControl ctrlGrid;
genericControl = Page.LoadControl(obj);
genericControl.ID = string.concat("gridControl");
Can there be any specific reasons for setting the ID using string.concat?
Can there be any performance hit associated with this?

I think you should use just:
genericControl.ID = "gridControl";
EDIT:
Take a look at string.Concat() method that will be used when you are passing one parameter:
public static string Concat(params string[] values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
int totalLength = 0;
string[] strArray = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
string str = values[i];
strArray[i] = (str == null) ? Empty : str;
totalLength += strArray[i].Length;
if (totalLength < 0)
{
throw new OutOfMemoryException();
}
}
return ConcatArray(strArray, totalLength);
}
So yes, it has performance overhead and better to use just string.

Related

How to use GUID as Primary Key with System.Data.Sqlite

I'm not saying it's advisable, but sometimes you inherit something which just needs to work. In this case it's Guids for Primary Keys...
Out of the box, you'll get an error about System.Guid not working with byte[] (or String if you're using BinaryGUID=False).
To fix this, you need to intercept byte[] arrays (or strings) and instead return Guid type. This is possible with the System.Data.Sqlite provider.
First
using System.Data.SQLite;
Then, put this in the constructor of your code-first db context:
var con = (SQLiteConnection)base.Database.Connection;
var bind = System.Data.SQLite.SQLiteTypeCallbacks.Create(
null,
new SQLiteReadValueCallback(GuidInterceptor), null, null);
con.SetTypeCallbacks("uniqueidentifier", bind);
con.SetTypeCallbacks("", bind); //Sometimes, the system just doesn't know
con.Flags |= SQLiteConnectionFlags.UseConnectionReadValueCallbacks;
And then this is the magic function:
private void GuidInterceptor(SQLiteConvert convert, SQLiteDataReader reader, SQLiteConnectionFlags flags, SQLiteReadEventArgs args, string typename, int index, object userdata, out bool complete)
{
complete = false;
if (typename == "uniqueidentifier")
{
var e = (SQLiteReadValueEventArgs)args;
var o = reader.GetGuid(index);
e.Value.Value = o;
e.Value.GuidValue = o;
complete = true;
}
else
{
var o = reader.GetValue(index);
if (o is byte[])
{
var b = (byte[])o;
if (b.Length == 16)
{
var e = (SQLiteReadValueEventArgs)args;
var g = new Guid(b);
e.Value.Value = g;
e.Value.GuidValue = g;
complete = true;
}
}
else if (o is string)
{
var s = (string)o;
if (s.Length == 36)
{
var e = (SQLiteReadValueEventArgs)args;
var goGuid = (e.MethodName == "GetGuid");
if (!goGuid)
goGuid = (s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-');
Guid g;
if (goGuid && Guid.TryParse(s, out g))
{
e.Value.Value = g;
e.Value.GuidValue = g;
complete = true;
}
else
{
}
}
}
}
}
That only fixes reading in of data. If you try to .Where() on a Guid member, and you're using BinaryGUID=True no rows will be returned (when there should be). For now, you'll need BinaryGUID=False, which does take up more space, but it's a simple solution.
If you can help it, try and define your Guid properties instead as:
[Key]
[MaxLength(16)]
[MinLength(16)]
public byte[] AccountUserId { get; set; }
You'll be forced to call guidValue.ToByteArray() in your application layer. You might be able to create some helpers to you're not having to call that function. Having your own custom function proxy for creating and parsing Guids may help, so you can easily change the implementation.
In my case, I don't have the luxury of time to convert all the Guid properties and usages to byte[]

Trouble with getting codes for Huffman Tree

I need to create the codes to compress a Huffman Tree. (O if you traverse left 1 if you traverse right.)
Right now the codes array will get the correct first code, but afterwards will only return null.
I am not allowed to use any instance/global variables or any predefined java classes besides array and arrayList
public static String compress(final BinaryNodeInterface<Character> root, final String message)
{
String[] codes;
ArrayList<Character> letter = new ArrayList<Character>();
String codeString = "";
boolean addChar=true;
for(int i =0; i<message.length();i++)
{
for(int j=0;j<letter.size();j++)
if(message.charAt(i)==letter.get(j))
addChar=false;
else
addChar=true;
if(addChar)
letter.add(message.charAt(i));
}
codes = new String[letter.size()];
for(int i=0;i<letter.size();i++)
codes[i]=(getPath(root,letter.get(i),""));
return ""; // Do not forget to change this line!!!
}
private static String getPath(final BinaryNodeInterface<Character> root, char toFind, String path)
{
String result;
if (! root.isLeaf()) {
if ((result = getPath(root.getLeftChild(),toFind, path + '0')) == null) {
result = getPath(root.getLeftChild(),toFind, path + '1');
}
}
else {
result = (toFind == root.getData()) ? path : null;
}
return result;
}
You don't seem to be visiting the right sub child. Change
result = getPath(root.getLeftChild(),toFind, path + '1');
to
result = getPath(root.getRightChild(),toFind, path + '1');

programming logic problem

I need a function that can give me all possible combinations of a array back.
Example:
$source = array('a', 'b', 'c');
$target = thisiswhatisearch($source);
Now the $target should look like:
array('a','b','c','ab','ac','cb','abc')
I dont need the aa, bb, cc.
I also dont need the the ba, ca, acb.. because the order isn't important to me.
Thanks for any help.
Tried to be language agnostic but i guess its C like:
function combinations(array arr)
{
combos = array();
for (int i=1; i<2**arr.size(); i++)
{
int x = i;
int c = 0;
str = "";
while(x>0)
{
int rem = x % 2;
if(rem == 1)
str += arr[c];
x = x / 2;
c++;
}
combos.add(str);
}
return combos;
}
The Wikipedia entry for Combination has a link to C code that does this.
That's an out of the mind solution. It is probably not the fastest and cleanest one, but it kind of works. It's in Java, because I had it open:
public class Combination {
public static void main(String[] args) {
String[] source = {"a","b","c"};
List<String> result = combineMe(new ArrayList<String>(Arrays.asList(source)));
for (String string : result) {
System.out.println(string);
}
}
public static List<String> combineMe(List<String> source) {
List<String> result = new ArrayList<String>();
if (source.size()==0) {
result.add("");
return result;
}else{
String tmp = source.remove(0);
source = combineMe(source);
for (String string : source) {
result.add(("" + string).trim());
result.add(tmp + string);
}
}
return result;
}
}
The first entry in the resulting list is a fake one, and needs to be removed at the end

Use MatchPattern property of FindMatchingFiles workflow activity

I'm customizing the default workflow of build process template using TFS 2010 Team Build. There is an activity named FindMatchingFiles allows to search for specific files with a pattern defined in MatchPattern property. It works if I only specify one file extension. Example:
String.Format("{0}\\**\\\*.msi", SourcesDirectory)
But I would like to include *.exe as well. Trying following pattern but it doesn't work:
String.Format("{0}\\**\\\*.(msi|exe)", SourcesDirectory)
Anyone could show me how to correct it?
You can use String.Format("{0}\**\*.msi;{0}\**\*.exe", SourcesDirectory)
The FindMatchingFiles activity's MatchPattern property uses the
Syntax that is supported by the searchPattern argument of the Directory.GetFiles(String, String) method.
That means that you can't combine multiple extensions. You'll need to call the FindMatchingFiles activity twice. You can then combine the results of those two calls when you use them (i.e. if your results are msiFiles and exeFiles, you can use msiFiles.Concat(exeFiles) as the input to a ForEach).
However, as you can see with #antwoord's answer, the activity does actually seem to accept a semi-colon delimited list of patterns, unlike Directory.GetFiles.
FindMatchingFiles has some strange search pattern. Here is the code (decompiled using ILSpy) so you can test your search patterns without having to kick off a new build.
It contains a hardcoded root dir at the following location (Z:)
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
Code:
using System;
using System.Collections.Generic;
using System.IO;
namespace DirectoryGetFiles
{
//// Use the FindMatchingFiles activity to find files. Specify the search criteria in the MatchPattern (String) property.
//// In this property, you can specify an argument that includes the following elements:
//// Syntax that is supported by the searchPattern argument of the Directory GetFiles(String, String) method.
////
//// ** to specify a recursive search. For example:
//// To search the sources directory for text files, you could specify something that resembles the following
//// value for the MatchPattern property: String.Format("{0}\**\*.txt", SourcesDirectory).
////
//// To search the sources directory for text files in one or more subdirectories that are called txtfiles,
//// you could specify something that resembles the following value for the MatchPattern property:
//// String.Format("{0}\**\txtfiles\*.txt", SourcesDirectory).
class Program
{
static void Main(string[] args)
{
string searchPattern = #"_PublishedWebsites\Web\Scripts\jasmine-specs**\*.js";
var results = Execute(searchPattern);
foreach (var i in results)
{
Console.WriteLine("found: {0}", i);
}
Console.WriteLine("Done...");
Console.ReadLine();
}
private static IEnumerable<string> Execute(string pattern)
{
string text = pattern;
text = text.Replace(";;", "\0");
var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] array = text.Split(new char[]
{
';'
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
string text3 = text2.Replace("\0", ";");
if (IsValidPattern(text3))
{
List<string> list = ComputeMatchingPaths(text3);
if (list.Count > 0)
{
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
hashSet.Add(current);
}
goto IL_15C;
}
}
////Message = ActivitiesResources.Format("NoMatchesForSearchPattern", new object[]
}
else
{
//// Message = ActivitiesResources.Format("InvalidSearchPattern", new object[]
}
IL_15C: ;
}
return hashSet;//.OrderBy((string x) => x, FileSpec.TopDownComparer);
}
private static bool IsValidPattern(string pattern)
{
string text = "**" + Path.DirectorySeparatorChar;
int num = pattern.IndexOf(text, StringComparison.Ordinal);
return (num < 0 || (pattern.IndexOf(text, num + text.Length, StringComparison.OrdinalIgnoreCase) <= 0 && pattern.IndexOf(Path.DirectorySeparatorChar, num + text.Length) <= 0)) && pattern[pattern.Length - 1] != Path.DirectorySeparatorChar;
}
private static List<string> ComputeMatchingPaths(string matchPattern)
{
List<string> list = new List<string>();
string text = "**" + Path.DirectorySeparatorChar;
int num = matchPattern.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase);
if (num >= 0)
{
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
string searchPattern = matchPattern.Substring(num + text.Length);
using (List<string>.Enumerator enumerator = matchingDirectories.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
list.AddRange(Directory.GetFiles(current, searchPattern, SearchOption.AllDirectories));
}
return list;
}
}
int num2 = matchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (num2 >= 0)
{
List<string> matchingDirectories2 = GetMatchingDirectories(string.Empty, matchPattern.Substring(0, num2 + 1), 0);
string searchPattern2 = matchPattern.Substring(num2 + 1);
using (List<string>.Enumerator enumerator2 = matchingDirectories2.GetEnumerator())
{
while (enumerator2.MoveNext())
{
string current2 = enumerator2.Current;
try
{
list.AddRange(Directory.GetFiles(current2, searchPattern2, SearchOption.TopDirectoryOnly));
}
catch
{
}
}
return list;
}
}
try
{
list.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), matchPattern, SearchOption.TopDirectoryOnly));
}
catch
{
}
return list;
}
private static List<string> GetMatchingDirectories(string rootDir, string pattern, int level)
{
if (level > 129)
{
return new List<string>();
}
List<string> list = new List<string>();
int num = pattern.IndexOf('*');
if (num >= 0)
{
int num2 = pattern.Substring(0, num).LastIndexOf(Path.DirectorySeparatorChar);
string text = (num2 >= 0) ? Path.Combine(rootDir, pattern.Substring(0, num2 + 1)) : rootDir;
if (text.Equals(string.Empty))
{
text = Directory.GetCurrentDirectory();
}
int num3 = pattern.IndexOf(Path.DirectorySeparatorChar, num);
if (num3 < 0)
{
num3 = pattern.Length;
}
string searchPattern = pattern.Substring(num2 + 1, num3 - num2 - 1);
try
{
string[] directories = Directory.GetDirectories(text, searchPattern, SearchOption.TopDirectoryOnly);
if (num3 < pattern.Length - 1)
{
string pattern2 = pattern.Substring(num3 + 1);
string[] array = directories;
for (int i = 0; i < array.Length; i++)
{
string rootDir2 = array[i];
list.AddRange(GetMatchingDirectories(rootDir2, pattern2, level + 1));
}
}
else
{
list.AddRange(directories);
}
return list;
}
catch
{
return list;
}
}
string text2 = Path.Combine(rootDir, pattern);
if (text2.Equals(string.Empty))
{
list.Add(Directory.GetCurrentDirectory());
}
else
{
if (Directory.Exists(text2))
{
list.Add(Path.GetFullPath(text2));
}
}
return list;
}
}
}

Generic Object to '|'-separated string serialization

I have written this class-methods for .net 2.0 to create objects from '|'-separated strings and vise-versa.
But the problem is, they are not giving right results in case of Inherted types, i.e. inherited properties are coming last and the sequence of the data supplied in the form of a '|'-separated string is not working.
For example:
class A
{
int ID;
}
class B : A
{
string Name;
}
the string is "1|John". the methods are reading as the name==1 and ID=="John".
Please tell me how to do it.
public class ObjectConverter<T>
{
public static T TextToObject(string text)
{
T obj = Activator.CreateInstance<T>();
string[] data = text.Split('|');
PropertyInfo[] props = typeof(T).GetProperties();
int objectPropertiesLength = props.Length;
int i = 0;
if (data.Length == objectPropertiesLength)
{
for (i = 0; i < objectPropertiesLength; i++)
{
props[i].SetValue(obj, data[i], null);
}
}
return obj;
}
public static string ObjectToText(T obj)
{
StringBuilder sb = new StringBuilder();
Type t = typeof(T);
PropertyInfo[] props = t.GetProperties();
int i = 0;
foreach (PropertyInfo pi in props)
{
object obj2 = props[i++].GetValue(obj, null);
sb.Append(obj2.ToString() + "|");
}
sb = sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}
I don't think the runtime assures you that when you call getproperties the property info objects will always be in the same order. You will need to do something like get the list of property names sort them and use the same sorting for serialization and deserialization .
There are at least 3 ways to serialize object built into .net is there a reason why you are not using one of those

Resources