Thursday, March 3, 2011

Do you have your own 'utils' dll and what do you keep there?

I can start with my own .NET dll. I have a dll I use in all my web projects (around 10) and I have util classes for FTP, zip, imageresizing, extensionmethods and a generic singleton class.

I think it is a common practice and I just thought it would be interesting to hear what people put in their 'Utils' dlls

EDIT: What small code gems do you have that have made you much more productive with lesser code?

These extension methods are pretty useful for me when parsing nullable form input before putting into the database

        public static int? ToInt(this string input) 
        {
            int val;
            if (int.TryParse(input, out val))
                return val;
            return null;
        }

        public static DateTime? ToDate(this string input)
        {
            DateTime val;
            if (DateTime.TryParse(input, out val))
                return val;
            return null;
        }

        public static decimal? ToDecimal(this string input)
        {
            decimal val;
            if (decimal.TryParse(input, out val))
                return val;
            return null;
        }
From stackoverflow
  • I have only just really started mine but at the moment it mostly contains just common extension methods that I use all the time. Stuff like "ThrowIfNull()" so I don't have to do heaps of if statements every time I want to check for nulls.

    I also have a playground project which just has any ideas that I am toying around with but I'm not 100% sure that they will even work.

    Chris Lively : Just an observation, but why bother with ThrowIfNull() when simply attempting to access members of a null object will throw an exception automatically?
    Nathan W : its mainly just so that I can throw any exception I want if the member is null with custom messages rather then letting the go on and then throw with a argunullexception with no description.
  • I've been collecting for years. This started out as a set of VBScript routines which I have since converted to VB6. This is a COM DLL, so I can use it almost anywhere in almost any language. I've spared you the boredom of all the enums.

    EDIT: I agree in principle with Chris Lively's comment on a previous posting in this section. However, as I said in the comments, if the work I am doing was .NET related, I'd certainly be tossing my stuff for what, I assume, is best of breed. However, in my case, .NET is too readily decompiled (making it a kind of ersatz open source) and my employer wants to protect his intellectual property.

    (Autogenerated by TLViewer, © Mark Pryor 2000-2003) 
    
    Library: Std
     P:\other\StdLib\StdLib.dll 
     Description: Std 
    
    coclass Drives
    
    Function DriveType(ByVal sDrv As String) As String
    
    
    coclass Arrays
    
    Function AAdd(aToThis ,ByVal xAddThis ) As Integer
    
    Function AAdd_PostIncrement(a , ByVal X ) As Variant
    
    Function AAdd_PreIncrement(a , ByVal X ) As Variant
    
    Function AMax(aVec ) As Variant
    
    Function AMin(aVec ) As Variant
    
    Sub DeleteFirst(anArray )
    
    Sub DeleteLast(anArray )
    
    Sub DeleteNth(anArray , ByVal nElement As Long)
    
    Function GenerateRange(nBot As Double, nTop As Double, [nStep As Double = 1]) As Variant
    
    Function GenerateRangeFromString(sRange ) As Variant
    
    Function InArray(sItem , aList ) As Boolean
    
    Function Reverse1DArray(aInput ) As Variant
    
    Function ShowStructure(vToShow ) As String
    
    Function StrInArray(sItem , aList , [bCaseInsens As Boolean = True]) As String
    
    
    coclass CmdLine
    
    Property AppExeName([BaseOnly As Boolean = False]) As String [Get/o]
    
    Property AppPath As String [Get/o]
    
    Property Argument(ByVal Which As Long) As String [Get/o]
    
    Property Arguments As Long [Get/o]
    
    Property CaseSensitive As Boolean [Get/Let]
    
    Function FlaggedArg(ByVal Flag As String) As String
    
    Function FlagPresent(ByVal Flag As String) As Long
    
    Function FlagPresentFromList(Flags () As Variant) As Boolean
    
    Sub Refresh()
    
    Function ToString() As String
    
    
    coclass BigString
    
    Sub ClearStr()
    
    Function GetStr([ByVal vJoiner = ]) As String
    
    Function GetStrArray() As Variant
    
    Sub PutStr(ByVal vString )
    
    
    coclass Config
    
    Sub Define(sKey , sValue )
    
    Property gsFilename As String [Get/Let]
    
    Function List(sFilter ) As String
    
    Function Load(sFile ) As Boolean
    
    Function LoadW(sFile ) As Boolean
    
    Function Recall(sKey ) As Variant
    
    Function RecallElse(sKey , sDefault ) As Variant
    
    Sub Save([sFile = ], [bAsAnsi = False])
    
    Sub SaveW([sFile = ], [bAsAnsi = False])
    
    
    coclass Collections
    
    Function Add(vData , [sKey ]) As _Variable 
    
    Property AddOnly As Boolean [Get/Let]
    
    Function Count() As Long
    
    Function Exists(vntIndexKey ) As Boolean
    
    Property Item(vntIndexKey ) As _Variable  [Get/o]
    
    Function Items() As Variant
    
    Function Keys() As Variant
    
    Sub Modify(sValue , sKey )
    
    Property NewEnum As stdole.IUnknown  [Get/o]
    
    Sub Remove(vntIndexKey )
    
    
    coclass Computers
    
    Function ComputerName() As String
    
    Function ExistsFolder(sComputer As String, sDir As String) As Boolean
    
    Function GetComputers(sDomain As String)() As Variant
    
    Function GetDomainComputers(ByVal strDomain As String)() As Variant
    
    Function GetNBT(sComputer As String) As String
    
    Function GetNBTA(sIPAddr As String) As String
    
    Function GetNetView(sDomain As String) As String
    
    Function GetOnlineComputers(sDomain As String)() As Variant
    
    Function GetRemoteEnvironment(sComputer )() As Variant
    
    Function GetSpecs(sComputer As String) As String
    
    Function GetTheComputerName() As String
    
    Function ResolveIP(sName As String) As String
    
    
    coclass Logic
    
    Function IIF(bCondition As Boolean, vTrue , vFalse ) As Variant
    
    
    coclass Decimals
    
    Property Dec As Variant [Get/Let]
    
    
    coclass Domains
    
    Function GetAvailableNTDomains()() As Variant
    
    
    coclass Database
    
    Sub CreateDatabase(sFile As String)
    
    Sub CreateIndex(ByVal oDb  As ADODB.Connection, sSpec As String)
    
    Sub CreateStructure(ByVal oDb  As ADODB.Connection, sSpec As String)
    
    Function OpenDatabase(theFile As String) As ADODB._Connection 
    
    Function OpenRecordSet(ByVal oDb  As ADODB.Connection, sQuery As String) As ADODB._Recordset 
    
    
    coclass DateTime
    
    Function dbDate(vDate ) As String
    
    Function GetGmtTime([StartingDate ]) As Date
    
    Function GetTimeDifference() As Long
    
    Function GetTimeHere(gmtTime As Date) As Date
    
    Function InternetTimeToVbLocalTime(ByVal DateString As String) As Date
    
    
    coclass Wallpaper
    
    Function ActiveDesktopSetWallpaper(ByVal strFile As String) As Boolean
    
    Sub At(ByVal nX As Integer, ByVal nY As Integer)
    
    Sub AtSay(ByVal nX As Integer, ByVal nY As Integer, ByVal sText As String)
    
    Sub Attributes(ByVal sAttribList As String)
    
    Sub Colour(ByVal iFGColour As Long, ByVal iBGColour As Long)
    
    Sub Dimensions(ByVal nHeight As Integer, ByVal nWidth As Integer)
    
    Sub Font(ByVal sName As String, ByVal iSize As Integer)
    
    Function LoadPic(sFilename As String, [nDestX As Integer = ], [nDestY As Integer = ]) As Variant
    
    Property Picture As Object [Get/Set]
    
    Sub SavePic(sFilename As String, [iType As Integer = 1])
    
    Sub Say(ByVal sText As String)
    
    Sub ScaleMode(ByVal iMode As Integer)
    
    Function TextHeight(ByVal sText As String) As Integer
    
    Function TextWidth(ByVal sText As String) As Integer
    
    
    coclass Excel
    
    Sub ExcelColumnNames(aHeadings () As Variant, [bBold As Boolean = True])
    
    Sub ExcelNewSheet()
    
    Sub ExcelStart([bHidden As Boolean = False])
    
    
    coclass StopWatch
    
    Sub Finish()
    
    Function FinishTime() As Date
    
    Function LapTime() As String
    
    Function Seconds() As Integer
    
    Sub Start()
    
    Function StartTime() As Date
    
    
    coclass Environments
    
    Function GetProcessEnv(strEnvVar As String) As String
    
    Function GetSystemEnv(strEnvVar As String) As String
    
    Function GetUserEnv(strEnvVar As String) As String
    
    Function GetVolatileEnv(strEnvVar As String) As String
    
    
    coclass Schedule
    
    Function AddTask(strTime , strCommand , [enDaysInWeek As ENUM_WEEKDAYS  = ], [strDaysInMonth = ], [RunInteractive As Boolean = True], [ReOccuring As Boolean = True]) As Long
    
    Function DeleteTask(lngID As Long) As Boolean
    
    Function GetNameOfComputer() As String
    
    
    coclass SymbolTable
    
    Function Append(sName , sValue ) As String
    
    Sub Clear()
    
    Function Increment(sName ) As Integer
    
    Function IsSym(sName ) As Boolean
    
    Function Keys()() As Variant
    
    Sub Parse(sData , sSep )
    
    Function Recall(sName ) As Variant
    
    Sub Remove(sData )
    
    Sub Store(sName , vValue )
    
    Sub StoreDup(sName , xValue )
    
    Sub StoreDup2(sName , xValue )
    
    Function SymList() As Variant
    
    Function SymListText() As String
    
    
    coclass Files
    
    Function CollectFiles(sDirectory , sFileType ) As Variant
    
    Sub DeleteFile(ByVal cFilename )
    
    Function Exists(sFile ) As Boolean
    
    Function FileHasBeenModified(sFile As String, dThen As Date) As Boolean
    
    Function FileModificationDate(sFile As String) As Date
    
    Function IsUTF16LE(sFile As String) As Boolean
    
    Function RandomInputFile(sExt As String) As String
    
    Function RandomOutputFile(sRandomInputFile As String, sExt As String) As String
    
    Function ReadFileA(FileName ) As String
    
    Function ReadFileE(FileName ) As String
    
    Function ReadFileU(FileName ) As String
    
    Function ReadFirstLineA(FileName ) As Variant
    
    Function ReadFirstLineE(FileName ) As String
    
    Function ReadFirstLineU(FileName ) As String
    
    Sub WriteFileA(sFilename , sContents , nMode As Long)
    
    Sub WriteFileB(sFilename , nOffset As Long, vData )
    
    Sub WriteFileU(sFilename , sContents , nMode As Long)
    
    
    coclass System
    
    Function AvailableDesktopDimensions() As Variant
    
    Function CaptureDOS(sCommand , [bSynch As Boolean = True]) As Variant
    
    Function ConsoleWrite(sText As String) As Long
    
    Function ConsoleWriteLine(sText As String) As Long
    
    Function CreateGUID() As String
    
    Function DesktopDimensions() As Variant
    
    Function DoEventsSeconds(nSeconds As Integer) As Integer
    
    Sub DoEventsSeconds2(iSeconds As Integer)
    
    Function GetTheWindowsDirectory() As String
    
    Function GetUUID(sUuid As String) As Boolean
    
    Function KillProcess(ProcessName As String) As Boolean
    
    Sub Navigate(ByVal NavTo As String)
    
    Function SetProcessPriority(sProcess As String, nPriority As EPROCESS_PRIORITY ) As Boolean
    
    Function ShellEx(ByVal sFile As String, [eShowCmd As EShellShowConstants  = essSW_SHOWDEFAULT], [ByVal sParameters As String = ], [ByVal sDefaultDir As String = ], [sOperation As String = "open"], [Owner As Long = ]) As Boolean
    
    Sub Sleep(nMilli As Integer)
    
    Function SystemDefaultUILanguage() As Long
    
    Function ThreadLocale() As Long
    
    
    coclass Groups
    
    Function GetComputerGroups(ByVal strComputerName As String)() As Variant
    
    Function GetDefaultNamingContext() As String
    
    Function GetGroups()() As Variant
    
    
    coclass Help
    
    Function HHDisplayHeadTopic(ByVal lHwnd As Long) As Long
    
    Function HHDisplaySearch(ByVal lHwnd As Long, [toSearch As String = ]) As Long
    
    Function HHHelpContents(ByVal lHwnd As Long) As Long
    
    Function HHHelpIndex(ByVal lHwnd As Long, [toSearch As String = ]) As Long
    
    Sub HHInitialize()
    
    Function HHKeywordLookup(ByVal lHwnd As Long, [sKeyword As String = ]) As Long
    
    Sub HHUninitialize()
    
    Property sHelpFile As String [Get/Let]
    
    
    coclass Number
    
    Function IntegerToUnsigned(Value As Integer) As Long
    
    Function LongToUnsigned(Value As Long) As Double
    
    Function UnsignedToInteger(Value As Long) As Integer
    
    Function UnsignedToLong(Value As Double) As Long
    
    
    coclass IEDisplay
    
    Sub Display(sMsg As String, nMillisec As Integer)
    
    Sub Init(sPosition )
    
    Property sName As String [Get/Let]
    
    
    coclass Temp
    
    Function GetTempFileName([sSeed As String = ]) As String
    
    Function LocGetFilePath(ByVal iCFName As String) As String
    
    Function TempDir() As String
    
    Function TempDirWide() As String
    
    Function TempFile(Create As Boolean, [lpPrefixString ], [lpszPath ]) As String
    
    Function UnicodeTempFile(ByVal iFileName As String) As String
    
    
    coclass INI
    
    Sub Clear()
    
    Function GetValue(sSection As String, sKey As String, strDefault As String) As String
    
    Function HasSection(sSection As String) As Boolean
    
    Function Load(sIniName As String) As Boolean
    
    Function ReadINIA(sSection , sKeyName , sINIFileName ) As String
    
    Function ReadINIU(sSection As String, sKeyName As String, sINIFileName As String) As String
    
    Function WriteINIA(sSection , sKeyName , sNewString , sINIFileName ) As Boolean
    
    Function WriteINIU(sSection As String, sKeyName As String, sNewString As String, sINIFileName As String) As Boolean
    
    
    coclass Variable
    
    Property Name As Variant [Get/Let/Set]
    
    Property Value As Variant [Get/Let/Set]
    
    
    coclass Mouse
    
    Function Between(ByVal nNumber As Integer, ByVal nLowerBound As Integer, ByVal nUpperBound As Integer) As Boolean
    
    Function MouseX([ByVal hWnd As Long = ]) As Long
    
    Function MouseY([ByVal hWnd As Long = ]) As Long
    
    
    coclass Traces
    
    Sub ClearTrace()
    
    Sub Trace([ByVal sTag = "!@#$%^&*()_"])
    
    Property TraceFile As String [Get/Let]
    
    Property Tracing As Boolean [Get/Let]
    
    
    coclass Registry
    
    Property ClassKey As ERegistryClassConstants  [Get/Let]
    
    Sub CreateAdditionalEXEAssociations(ByVal sClassName As String, vItems () As Variant)
    
    Sub CreateEXEAssociation(ByVal sExePath As String, ByVal sClassName As String, ByVal sClassDescription As String, ByVal sAssociation As String, [ByVal sOpenMenuText As String = "&Open"], [ByVal bSupportPrint As Boolean = False], [ByVal sPrintMenuText As String = "&Print"], [ByVal bSupportNew As Boolean = False], [ByVal sNewMenuText As String = "&New"], [ByVal bSupportInstall As Boolean = False], [ByVal sInstallMenuText As String = ], [ByVal lDefaultIconIndex As Long = -1])
    
    Function CreateKey() As Boolean
    
    Property Default As Variant [Get/Let]
    
    Function DeleteKey() As Boolean
    
    Function DeleteValue() As Boolean
    
    Function EnumerateSections(sSect () As String, iSectCount As Long) As Boolean
    
    Function EnumerateValues(sKeyNames () As String, iKeyCount As Long) As Boolean
    
    Property KeyExists As Boolean [Get/o]
    
    Property Machine As String [Get/Let]
    
    Property SectionKey As String [Get/Let]
    
    Property Value As Variant [Get/Let]
    
    Property ValueEx(ClassKey As ERegistryClassConstants , SectionKey As String, ValueKey As String, ValueType As ERegistryValueTypes , Default ) As Variant [Get/Let]
    
    Property ValueKey As String [Get/Let]
    
    Property ValueType As ERegistryValueTypes  [Get/Let]
    
    
    coclass Users
    
    Function GetComputerUsers(ByVal strComputerName As String)() As Variant
    
    Function GetComputerUsers2(ByVal strComputerName )() As Variant
    
    Function GetDomainUser(sComputer As String) As String
    
    Function GetLoginProfiles(sComputer )() As Variant
    
    Function GetMac(sDevice ) As String
    
    Function GetNameAndDescription(spDomain As String, sUsername As String) As String
    
    Function GetOUofUser(sDomain As String, sUsername As String) As String
    
    
    coclass Sort
    
    Sub heapsort(aVec )
    
    Sub quicksort(aVec )
    
    Sub shellsort(a0 , [bAscending As Boolean = True])
    
    Sub shellSortOnField(aVec , ByVal nField As Integer, ByVal sFieldSep , [nComparisonType As SSOF_COMPARISON  = SSOF_NUMERICAL])
    
    Function sorted()() As Variant
    
    
    coclass Strings
    
    Function AnyOf(sText , nOperator As AO_COMPARATORS , sChar ) As Boolean
    
    Function AnyOfList(sText , nOperator As AO_COMPARATORS , aChar ) As Boolean
    
    Function AsString(X ) As String
    
    Function BeginsWith(sText , sBeginning , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function Between(sText , sBegin , sEnd ) As String
    
    Function ByteArrayToString(aBytes () As Byte) As String
    
    Function ComprehendCSV(sText ) As Variant
    
    Function Contains(sText , sChunk , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function CountFields(strText , strDelim ) As Integer
    
    Function DQ(s ) As String
    
    Function EndsWith(sText , sEnding , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function EndsWithSet(sText , vEnding , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function FirstLineOf(sData ) As String
    
    Function FirstWord(sText ) As String
    
    Function ForceExtension(sFilename , sExtension ) As String
    
    Function HexDump(sData ) As String
    
    Function HTMLWrap(sTag , sContent ) As String
    
    Function LastLineOf(sData ) As String
    
    Function LeftFill(sText , nLen , sFill ) As String
    
    Function LeftOf(sText , sItem ) As String
    
    Function LeftOfLast(sText , sItem ) As String
    
    Function NthField(sText , sDelimiter , nReqdField ) As String
    
    Function NthLineOf(n As Integer, sData ) As String
    
    Function RemoveSpaces(sText ) As String
    
    Function Reverse(sText ) As String
    
    Function RightFill(sText , nLen , sFill ) As String
    
    Function RightOf(sText , sItem ) As String
    
    Function RightOfLast(sText , sItem ) As String
    
    Function SplitSet(ByVal sString , ByVal sSet ) As Variant
    
    Function StringConversion(s , n As Integer) As String
    
    Function StringMap(sText , aFrom , vTo ) As String
    
    Function StringToByteArray(ByVal sString )() As Byte
    
    Function Subst(sText , paArgList () As Variant) As String
    
    Function Subst2(sText , paArgList () As Variant) As String
    
    Function ZeroFill(nNum , nWidth ) As String
    
    Function Zerofill2(nNum ) As String
    
  • I think carrying utility assemblies beyond the current version of your language does more harm than good.

    The main reason is that as the language grows new methods and better ways of doing things are built in. By carrying around a utilities assembly, you will quickly end up with a lot of dead weight which may expose security problems.

    A prime example is boosts list of functions. A quick glance will show that .Net (just like most other languages) already cover at least 75% of that code.

    TT : That is a good point and I always try to remove or upgrade my Utils dll if a built in version of my code comes with the next .net library, but I also think many people have code that could be candidates for the next .net framework and it would be interesting to see examples of that.
    boost : It IS a good point. If the work I am doing was .NET related, I'd certainly be tossing my stuff for what, I assume, is best of breed. However, in my case, .NET is too readily decompiled (making it a kind of ersatz open source) and my employer wants to protect his intellectual property.
    Chris Lively : Anything can be reverse engineered. All you can do is try and make it difficult which is what obfuscation is all about and why professional products have been available in that era since way before .net and java.
  • I group my utilities by functionality. As a result, I don't have one utility DLL but rather a folder that contains several such assemblies, each one encapsulating one task (which usually includes more than just one class, in fact it usually includes a whole hierarchy).

    In the extreme case, this means that I have a DLL containing one declaration, namely the following one (plus documentation):

    namespace madrat.Common {
        public interface ICopyable<T> {
            T Copy();
        }
    }
    

    Notice that unlike the System.ICloneable interface, this one has well-defined semantics (deep copy) specified in the documentation.

    So why an extra DLL for this tiny declaration? Because it makes interoperability between other assemblies much easier.

0 comments:

Post a Comment