Senin, 14 Februari 2011

Powershell- Powertips: Setting Mouse Position

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

PowerShell can place the mouse cursor anywhere on your screen. Here's the code:
[system.Reflection.Assembly]::LoadWithPartialName("Microsoft.Forms") | Out-Null
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(500,100)
This would have placed the cursor at x=500 and y=100.

Powershell - Powertips: Comparing Services

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

Compare-Object can help when troubleshooting computers. For example, you should try this to compare the service status on two machines and find out where services are configured differently:
$machine1 = Get-Service –ComputerName server1-or-IP1
$machine2 = Get-Service –ComputerName server2-or-IP2
Compare-Object –ReferenceObject $machine1 –DifferenceObject $machine2 –Property Name,Status –passThru | Sort-Object Name | Select-Object Name, Status, MachineName

Powershell - Powertips: Checking Whether User or Group Exists

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

To find out whether a given local or domain user/group exists, you can simply use the static method Exists():
[ADSI]::Exists(’WinNT://./Tobias1‘)
This will check whether there is a local account named "Tobias1". To check domain accounts, you can simply replace "." with your domain name, or use LDAP:
[ADSI]::Exists(’LDAP://CN=Testuser,CN=Users,DC=YourDomain,DC=Com‘)

Powershell - Powertips: Reading Text Files as One Chunk

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs.

In a previous tip, you learned how to quickly read in text files. The result was a string array. If you want to read the text as one large string ultrafast, you can use this approach:
[System.IO.File]::ReadAllText(“c:\somefile.txt“)

Powershell - Powertips: Reading Text Files Fast

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

Let's assume you want to read a large text file. Let's create one:
Get-Process | Export-CLiXML $home\data.xml

(Dir $home\data.xml | Select-Object –expandProperty Length)/1MB
It should be roughly 5MB in size. Now let's read it using Get-Content:
Measure-Command { Get-Content $home\data.xml }
Now, you should check this out:
Measure-Command { [System.IO.File]::ReadLines(“$home\data.xml“) }
You will find the second approach is 20 times faster

Powershell - Powertips: Making Your Keyboard Sound like Typewriter

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

PowerShell is all about typing. But if you'd like to get back the old-fashioned typewriter sound, here is a freeware tool that can bring it back: http://www.grc.com/freeware/clickey.htm.

Powershell - Powertips: Disabling Automatic Page Files

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

If you would like to programmatically control page file settings, you can use WMI but must enable all privileges using -EnableAllPrivileges. The code below will disable automatic page files:
$c = Get-WmiObject Win32_ComputerSystem -EnableAllPrvileges
$c.AutomaticManagedPagefile = $false
$c.Put()

Powershell - Powertips: Eliminating Duplicate Words

I get emails from powershell.com that are worth sharing (and remembering). These are not my scripts. Signup for daily PowerTips here: http://powershell.com/cs/.

Let's assume you want to eliminate duplicate words in a text. Here is how you can do this:
'this text text contains duplicate words words following each other' -replace '\b(\w+)(\s+\1){1,}\b', '$1'

Powershell - Automate HTTP POST Process

I was trying to figure out a way to automate testing a form with HTTP POST. I found this link:
http://powershell.com/cs/blogs/tips/archive/2010/04/29/sending-post-data-via-powershell.aspx
It gave me the base and with just a few quick tweaks I got it running with the following script:
function spam{
$url = "http://www.theboard.com/post_item.aspx"
$parameters = "name=test=&subject=test&body=test body."

$http_request = New-Object -ComObject Msxml2.XMLHTTP
$http_request.open('POST', $url, $false)
$http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
$http_request.setRequestHeader("Content-length", $parameters.length)
$http_request.setRequestHeader("Connection", "close")
$http_request.send($parameters)
$http_request.statusText
}
To validate some load stress, I just automated the posting.
for($i = 0; $i -lt 100; $i++)
{
spam
Write-Host $i
}
I had gotten the parameters I needed to work with, $url and $parameters, by using LiveHttpHeaders with Firefox. All you have to do is save the output of your post and cut and paste.

Minggu, 13 Februari 2011

TSQL - Varbinary Cast

We use a web application to manage much of our system security. Much like Windows, we use a role based security system (think user groups). When creating new user groups we often reference standard user group names. Some of these names are stored in a Word document. So, when a hyphen (i.e., short dash) is entered into Word followed by a dash, it is automatically converted into an "en dash". This is when the single dash is expanded and looks "wider" than normal.

Since we run some scheduled tasks to regularly perform functions based on user group names this automatic formatting feature of Word becomes an issue. The script looks explicitly for the hyphen (ASCII decimal code 45/hexidecimal code 2D) but finds the en dash (ASCII decimal code 150/hexidecimal code 96). For reference, visit this site:
http://www.ascii-code.com/
to get an idea of what these characters are.

After suspecting this was the root cause some updates were not occurring, I wanted to find a way to validate my hunch via SQL directly. Knowing we were dealing with two characters that would appear similar in the web application, but, could be identified as unique via the hex values. I pulled up this link:
http://stackoverflow.com/questions/219245/converting-a-string-to-hex-in-sql
which lead me to come up with this query (the CAST is highlighted in orange):
SELECT usergroupname, CAST(usergroupname AS VARBINARY) FROM MyDatabase.dbo.MyTable
This provided me with a side by side string-to-hex relationship. I then created a new group with the hyphen (0x2D) and reran the query. I was able to use this as a good way to provide an explanatory email to my team members as to why they needed to be careful with the Word cut-and-paste technique.

TSQL - Search Column for PCI Cardholder Data

I needed to get my head around dynamically searching all fields in a given set of database tables for PCI Cardholder Data. I had previously come up with a rudimentary query to search for credit card numbers:
http://learningpcs.blogspot.com/2009/03/credit-cards.html
This time, however, I wanted to try and handle it all via SQL. For starters, I needed to determine which fields I wanted to work with. My initial query (from the link above) was:
SELECT SO.name, SC.name
FROM sysobjects AS SO
JOIN syscolumns AS SC
ON SO.ID = SC.ID
WHERE (SO.xtype = 'U') AND (SC.name LIKE '%_SUFFIX')
I needed something more powerful. I started with this link:
http://codesnippets.joyent.com/posts/show/337
The basic query provided here was:
SELECT table_name=sysobjects.name,
column_name=syscolumns.name,
datatype=systypes.name,
length=syscolumns.length
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U'
ORDER BY sysobjects.name,syscolumns.colid
Taking this to the next level on my system I looked as some specific fields and focused uniquely on field lengths at least 12 characters long since the shortest possible credit card number is 12 characters:
USE MyDatabase
GO

SELECT [Table Name] = sysobjects.name
,[Column Name] = syscolumns.name
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype = systypes.xtype
WHERE sysobjects.xtype='U' -- retrieve tables only
AND syscolumns.name like 'Prefix_[a-z]%' -- retrieve only data columns
AND sysobjects.name like 'NRS[0-9]%' -- retrieve only NRS tables
AND substring(sysobjects.name,2,4) IN (SELECT FolderName FROM MyDatabase.dbo.Folders WHERE FolderName <> 'Secondary')
AND syscolumns.length > 11 -- exclude anything possibly shorter than shortest CC Number
ORDER BY sysobjects.name, syscolumns.colid
I am working some more to try and use this as a the basis of a query that fills a temp table so I can then run a set-based query with a while loop to actually search each of the fields I cull with this query and store hits in a second temp table for review later. The query I originally used in my old post works fine but it has a lot of assumptions. I wanted to refine it some more with tweaks on:
  1. using a function to test each field that is a potential hit
  2. examine the hits with Luhn validity (assuming users entered the value correctly); see this SQL Team post
  3. use the Issuer Identification Number (IIN) with a case
  4. assume the use of multiple potential delimiters
Combining all of these to formulate a secondary level of testing, above and beyond the simple formula outlined in the old link, adds several levels of complication. For instance, we still use a lot of SQL Server 2000 engines, so, CLR integration is not much of an option. Hence, regular expression will be more difficult. Second, I don't want to totally tank the server's memory running an obnoxiously large query. I will probably hit the TSQL forums over at MSDN/Technet to get some assistance as much of the advanced functionality here (Luhn and regular expressions) will require folks with some more insight into the real guts of SQL Server than I have at this point. I'll put more posts down the road as I get a little more work done on this hypothetical function. A well-developed function to identify credit card numbers is something I suspect lots of folk would benefit from having worked out.

Powershell - Bruce Payette ql Function

While reviewing some of Shay Levy's Powershell on Luhn validation:
http://scriptolog.blogspot.com/2008/01/powershell-luhn-validation.html
I noticed a comment referring to Bruce Payette's ql function trick. Having never heard of this, I Googled a bit and found this:
http://blogs.msdn.com/b/powershell/archive/2007/03/01/year-of-the-pig-revisited-the-magic-of-ql.aspx
Using the following function:
function ql
{
$args
}
you can save yourself a lot of typing. For instance, if you want to just enter a long string within having to retype it, you can use this pattern:
function ql {$args}
ql Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog
which will then proceed to echo back all the content of the $args collection in order.
Pig
Rat
Ox
Tiger
Rabbit
Dragon
Snake
Horse
Goat
Monkey
Rooster
Dog
In the context of Shay's post, the commenter added this:
function ql{$args}
test-luhnnumber (ql 0 6 6 2 4 9 1 8 9 2 3)

Powershell - Delete Temporary Internet Files

I can't recall how I got interestd in trying to delete temporary internet files with Powershell, but, after much digging I came across this link:
http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/1511ac62-0d48-4c8e-837e-11940a5b7b94
After checking out the link, Richard's blog:
http://msmvps.com/blogs/richardsiddaway/archive/2010/07/12/cookie-time.aspx
had a great entry. I was originally looking to see if the inetcpl.cpl (http://blogs.techrepublic.com.com/window-on-windows/?p=574) some sort of COM interface, but, none ever surfaced. As I dug around the COM object I went through each level to get a feel for what sort of aspects of the object were exposed via the COM interface.

Here are my walkdown steps:

Create the reference:
$app = New-Object -ComObject Shell.Application

Get members of app to see what objects exist at that level
$app | gm


TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e}

Name MemberType Definition
---- ---------- ----------
AddToRecent Method void AddToRecent (Variant, string)
BrowseForFolder Method Folder BrowseForFolder (int, string, int, Variant)
CanStartStopService Method Variant CanStartStopService (string)
CascadeWindows Method void CascadeWindows ()
ControlPanelItem Method void ControlPanelItem (string)
EjectPC Method void EjectPC ()
Explore Method void Explore (Variant)
ExplorerPolicy Method Variant ExplorerPolicy (string)
FileRun Method void FileRun ()
FindComputer Method void FindComputer ()
FindFiles Method void FindFiles ()
FindPrinter Method void FindPrinter (string, string, string)
GetSetting Method bool GetSetting (int)
GetSystemInformation Method Variant GetSystemInformation (string)
Help Method void Help ()
IsRestricted Method int IsRestricted (string, string)
IsServiceRunning Method Variant IsServiceRunning (string)
MinimizeAll Method void MinimizeAll ()
NameSpace Method Folder NameSpace (Variant)
Open Method void Open (Variant)
RefreshMenu Method void RefreshMenu ()
ServiceStart Method Variant ServiceStart (string, Variant)
ServiceStop Method Variant ServiceStop (string, Variant)
SetTime Method void SetTime ()
ShellExecute Method void ShellExecute (string, Variant, Variant, Variant, Variant)
ShowBrowserBar Method Variant ShowBrowserBar (string, Variant)
ShutdownWindows Method void ShutdownWindows ()
Suspend Method void Suspend ()
TileHorizontally Method void TileHorizontally ()
TileVertically Method void TileVertically ()
ToggleDesktop Method void ToggleDesktop ()
TrayProperties Method void TrayProperties ()
UndoMinimizeALL Method void UndoMinimizeALL ()
Windows Method IDispatch Windows ()
WindowsSecurity Method void WindowsSecurity ()
WindowSwitcher Method void WindowSwitcher ()
Application Property IDispatch Application () {get}
Parent Property IDispatch Parent () {get}

Look at the $app.Namespace object (Shell.Application.Namespace):
$app.Namespace


MemberType : Method
OverloadDefinitions : {Folder NameSpace (Variant)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : Folder NameSpace (Variant)
Name : NameSpace
IsInstance : True

Examine the members:
$app.Namespace | gm


TypeName: System.Management.Automation.PSMethod

Name MemberType Definition
---- ---------- ----------
Copy Method System.Management.Automation.PSMemberInfo Copy()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Invoke Method System.Object Invoke(Params System.Object[] arguments)
ToString Method string ToString()
IsInstance Property System.Boolean IsInstance {get;}
MemberType Property System.Management.Automation.PSMemberTypes MemberType {get;}
Name Property System.String Name {get;}
OverloadDefinitions Property System.Collections.ObjectModel.Collection`1[[System.String, mscorlib, Version=2.0.0.0...
TypeNameOfValue Property System.String TypeNameOfValue {get;}
Value Property System.Object Value {get;set;}

Look specifically at the entries as noted in the blog:
$app.namespace(0x21)

Note: The output of decimal (21) and hex (0x21) references will yield different results:
$app.NameSpace(0x21)


Title : Cookies
Application : System.__ComObject
Parent :
ParentFolder : System.__ComObject
Self : System.__ComObject
OfflineStatus :
HaveToShowWebViewBarricade : False
ShowWebViewBarricade : False

versus this:
$app.NameSpace(21)

Title : Templates
Application : System.__ComObject
Parent :
ParentFolder : System.__ComObject
Self : System.__ComObject
OfflineStatus :
HaveToShowWebViewBarricade : False
ShowWebViewBarricade : False

Now, what's interesting is that, without the reference (shown above) I get a pretty bland member set. However, when I add the (0x21) reference and run Get-Member cmdlet, I see different objects:
$app.Namespace(0x21) | gm


TypeName: System.__ComObject#{a7ae5f64-c4d7-4d7f-9307-4d24ee54b841}

Name MemberType Definition
---- ---------- ----------
CopyHere Method void CopyHere (Variant, Variant)
DismissedWebViewBarricade Method void DismissedWebViewBarricade ()
GetDetailsOf Method string GetDetailsOf (Variant, int)
Items Method FolderItems Items ()
MoveHere Method void MoveHere (Variant, Variant)
NewFolder Method void NewFolder (string, Variant)
ParseName Method FolderItem ParseName (string)
Synchronize Method void Synchronize ()
Application Property IDispatch Application () {get}
HaveToShowWebViewBarricade Property bool HaveToShowWebViewBarricade () {get}
OfflineStatus Property int OfflineStatus () {get}
Parent Property IDispatch Parent () {get}
ParentFolder Property Folder ParentFolder () {get}
Self Property FolderItem Self () {get}
ShowWebViewBarricade Property bool ShowWebViewBarricade () {get} {set}
Title Property string Title () {get}

Taking this a level down I work with the Self property:
$app.Namespace(0x21).Self


Application : System.__ComObject
Parent : System.__ComObject
Name : Cookies
Path : C:\Users\Will\AppData\Roaming\Microsoft\Windows\Cookies
GetLink :
GetFolder : System.__ComObject
IsLink : False
IsFolder : True
IsFileSystem : True
IsBrowsable : False
ModifyDate : 1/18/2011 7:16:28 PM
Size : 0
Type : File folder

This actually gave me a good selection of objects when I ran the Get-Member cmdlet.
$app.Namespace(0x21).Self | gm


TypeName: System.__ComObject#{edc817aa-92b8-11d1-b075-00c04fc33aa5}

Name MemberType Definition
---- ---------- ----------
ExtendedProperty Method Variant ExtendedProperty (string)
InvokeVerb Method void InvokeVerb (Variant)
InvokeVerbEx Method void InvokeVerbEx (Variant, Variant)
Verbs Method FolderItemVerbs Verbs ()
Application Property IDispatch Application () {get}
GetFolder Property IDispatch GetFolder () {get}
GetLink Property IDispatch GetLink () {get}
IsBrowsable Property bool IsBrowsable () {get}
IsFileSystem Property bool IsFileSystem () {get}
IsFolder Property bool IsFolder () {get}
IsLink Property bool IsLink () {get}
ModifyDate Property Date ModifyDate () {get} {set}
Name Property string Name () {get} {set}
Parent Property IDispatch Parent () {get}
Path Property string Path () {get}
Size Property int Size () {get}
Type Property string Type () {get}

Taking this to the last noted level, Path, I was able to get very specific:
$app.Namespace(0x21).Self.Path
C:\Users\Will\AppData\Roaming\Microsoft\Windows\Cookies

The majority of the members at this level were really members of the File object:
$app.Namespace(0x21).Self.Path | gm

TypeName: System.String

Name MemberType Definition
---- ---------- ----------
Clone Method System.Object Clone()
CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB)
Contains Method bool Contains(string value)
CopyTo Method System.Void CopyTo(int sourceIndex, char[] destination, int destinationIndex,...
EndsWith Method bool EndsWith(string value), bool EndsWith(string value, System.StringCompari...
Equals Method bool Equals(System.Object obj), bool Equals(string value), bool Equals(string...
GetEnumerator Method System.CharEnumerator GetEnumerator()
GetHashCode Method int GetHashCode()
GetType Method type GetType()
GetTypeCode Method System.TypeCode GetTypeCode()
IndexOf Method int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf...
IndexOfAny Method int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i...
Insert Method string Insert(int startIndex, string value)
IsNormalized Method bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz...
LastIndexOf Method int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int...
LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI...
Normalize Method string Normalize(), string Normalize(System.Text.NormalizationForm normalizat...
PadLeft Method string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)
PadRight Method string PadRight(int totalWidth), string PadRight(int totalWidth, char padding...
Remove Method string Remove(int startIndex, int count), string Remove(int startIndex)
Replace Method string Replace(char oldChar, char newChar), string Replace(string oldValue, s...
Split Method string[] Split(Params char[] separator), string[] Split(char[] separator, int...
StartsWith Method bool StartsWith(string value), bool StartsWith(string value, System.StringCom...
Substring Method string Substring(int startIndex), string Substring(int startIndex, int length)
ToCharArray Method char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
ToLower Method string ToLower(), string ToLower(System.Globalization.CultureInfo culture)
ToLowerInvariant Method string ToLowerInvariant()
ToString Method string ToString(), string ToString(System.IFormatProvider provider)
ToUpper Method string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
ToUpperInvariant Method string ToUpperInvariant()
Trim Method string Trim(Params char[] trimChars), string Trim()
TrimEnd Method string TrimEnd(Params char[] trimChars)
TrimStart Method string TrimStart(Params char[] trimChars)
Chars ParameterizedProperty char Chars(int index) {get;}
Length Property System.Int32 Length {get;}

Out of curiousity, I wanted to see how many different folders paths I could get, so, I set up this loop:
$collection = @()
for($i = 1; $i -lt 1000; $i++)
{
$collection += $app.Namespace($i).Self.Path
}

foreach($i in $collection)
{
Write-Host $i
}

What turned out to be interesting that the output showed a pattern where, after every 256 lines (the same size as a uint) it would start repeating. Below are the entries I found with the corresponding numbers in front:
1 ::{871C5380-42A0-1069-A2EA-08002B30309D}
2 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
3 ::{26EE0668-A00A-44D7-9371-BEB064C98683}\0
4 ::{21EC2020-3AEA-1069-A2DD-08002B30309D}\::{2227A280-3AEA-1069-A2DE-08002B30309D}
5 C:\Users\Will\Documents
6 C:\Users\Will\Favorites
7 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
8 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Recent
9 C:\Users\Will\AppData\Roaming\Microsoft\Windows\SendTo
10 ::{645FF040-5081-101B-9F08-00AA002F954E}
11 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Start Menu
13 C:\Users\Will\Music
14 C:\Users\Will\Videos
16 C:\Users\Will\Desktop
17 ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
18 ::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}
19 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Network Shortcuts
20 C:\Windows\Fonts
21 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Templates
22 C:\ProgramData\Microsoft\Windows\Start Menu
23 C:\ProgramData\Microsoft\Windows\Start Menu\Programs
24 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
25 C:\Users\Public\Desktop
26 C:\Users\Will\AppData\Roaming
27 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
28 C:\Users\Will\AppData\Local
29 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
30 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
31 C:\Users\Will\Favorites
32 C:\Users\Will\AppData\Local\Microsoft\Windows\Temporary Internet Files
33 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Cookies
34 C:\Users\Will\AppData\Local\Microsoft\Windows\History
35 C:\ProgramData
36 C:\Windows
37 C:\Windows\System32
38 C:\Program Files
39 C:\Users\Will\Pictures
40 C:\Users\Will
41 C:\Windows\System32
42 C:\Program Files
43 C:\Program Files\Common Files
44 C:\Program Files\Common Files
45 C:\ProgramData\Microsoft\Windows\Templates
46 C:\Users\Public\Documents
47 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
48 C:\Users\Will\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
49 ::{21EC2020-3AEA-1069-A2DD-08002B30309D}\::{7007ACC7-3202-11D1-AAD2-00805FC1270E}
53 C:\Users\Public\Music
54 C:\Users\Public\Pictures
55 C:\Users\Public\Videos
56 C:\Windows\Resources
57 C:\ProgramData\OEM Links
58 C:\Users\Will\AppData\Local\Microsoft\Windows\Burn\Burn
61 ::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}

DNS - Where are settings stored?

After wrestling with some DNS issues I wanted to know where the DNS data was actually stored on a machine. It took me a while to find this link:
http://social.technet.microsoft.com/Forums/en-US/windowsserver2008r2networking/thread/7d7adbb7-f0a3-4292-9417-4024081dd782
Apparently you have to log onto the DNS server and look in the %SystemRoot%\System32\DNS\ directory; the file name I worked with was mydomain.myhost.com.dns where mydomain.myhost.com was the domain name of my environment. Basically, look for a file with the .dns extension. When I looked at the DNS server on our domain I realized it looked a lot like the regular hosts file found on client machines (%systemroot%\system32\drivers\etc\hosts), but, with significantly more entries. I don't know if the example from this link:
http://zytrax.com/books/dns/ch6/mydomain.html
is Windows or not (I suspect it's not since BIND is more of the UNIX universe) but it gives a good taste of a sample domain:
$TTL 86400 ; 24 hours could have been written as 24h or 1d
$ORIGIN example.com.
@ 1D IN SOA ns1.example.com. hostmaster.example.com. (
2002022401 ; serial
3H ; refresh
15 ; retry
1w ; expire
3h ; minimum
)a
IN NS ns1.example.com. ; in the domain
IN NS ns2.smokeyjoe.com. ; external to domain
IN MX 10 mail.another.com. ; external mail provider
; server host definitions
ns1 IN A 192.168.0.1 ;name server definition
www IN A 192.168.0.2 ;web server definition
ftp IN CNAME www.example.com. ;ftp server definition
; non server domain hosts
bill IN A 192.168.0.3
fred IN A 192.168.0.4

Powershell - Base64 Functions

Since I am slowly building up a Powershell Pen Testing suite, I wanted to grab a few fuzzing functions. The Base64 functions outlined here:
http://www.techmumbojumblog.com/?p=306
have been helpful for input and URL analysis. To save myself the trouble of reinventing this from time to time I am adding it to the $profile.AllUsersAllHosts profile on my machine to allow me to call the code I need in a jiffy. I am even aliasing them to make life easier. Here are the functions:
# http://www.techmumbojumblog.com/?p=306

function ConvertTo-Base64($string) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);

return $encoded;
}

function ConvertFrom-Base64($string) {
$bytes = [System.Convert]::FromBase64String($string);
$decoded = [System.Text.Encoding]::UTF8.GetString($bytes);

return $decoded;
}
and the aliases:

# Add aliases for Coversion functions

New-Alias -Name ct64 -Value ConvertTo-Base64 -Description "ConvertTo-Base64 alias" -Option AllScope
New-Alias -Name cf64 -Value ConvertFrom-Base64 -Description "ConvertFrom-Base64 alias" -Option AllScope

Powershell - WinNT Provider

I reimaged my Windows 7 machine and want to make a new account strictly to contain pen testing tools. Wondering how I could do this the Powershell way I started looking around. Most everything I found related to domain user management, i.e., LDAP and ADSI. In my case, I was not dealing with AD per se, but, rather the WinNT provider to add a local account. I stumbled onto this post:
http://www.vistax64.com/powershell/173919-add-built-account-local-group-using-winnt-adsi-provider.html
where Shay Levy added this little nugget:
$group = [ADSI]"WinNT://$env:COMPUTERNAME/Administrators,group"
$group.add("WINNT://NT AUTHORITY/SYSTEM")
I thought okay, great, I've got something to work with. My next step was MSDN to try and find some higher level info to work with. This link came up on Google, but, it really didn't get me far:
http://msdn.microsoft.com/en-us/library/aa746534(v=VS.85).aspx
I then searched for [ADSI]"WinNT Powershell and got an old Scripting Guys post that got me messing around in the right direction:
http://blogs.technet.com/b/heyscriptingguy/archive/2008/03/11/how-can-i-use-windows-powershell-to-add-a-domain-user-to-a-local-group.aspx
As is much more eloquently noted in the post, if you try and pass the reference to a variable and run a Get-Member cmdlet against it, you don't get very far.
$group = [ADSI]"WinNT://$env:COMPUTERNAME/Administrato
rs,group"
$group | gm


TypeName: Microsoft.PowerShell.Commands.MemberDefinition

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Definition Property System.String Definition {get;}
MemberType Property System.Management.Automation.PSMemberTypes MemberType {get;}
Name Property System.String Name {get;}
TypeName Property System.String TypeName {get;}
Now, if you use the PSBase reference, things start to open up a lot:
Likewise, if you go up one level and focus less on a specific group, but, rather, the machine itself, you see a lot of nice things to start playing with:
$machine = [ADSI]"WinNT://$env:COMPUTERNAME"
$machine | gm


TypeName: System.DirectoryServices.DirectoryEntry

Name MemberType Definition
---- ---------- ----------
ConvertDNWithBinaryToString CodeMethod static string ConvertDNWithBinaryToString(psobject deInstance, psobject dnWit...
ConvertLargeIntegerToInt64 CodeMethod static long ConvertLargeIntegerToInt64(psobject deInstance, psobject largeInt...
Division Property System.DirectoryServices.PropertyValueCollection Division {get;set;}
Name Property System.DirectoryServices.PropertyValueCollection Name {get;set;}
OperatingSystem Property System.DirectoryServices.PropertyValueCollection OperatingSystem {get;set;}
OperatingSystemVersion Property System.DirectoryServices.PropertyValueCollection OperatingSystemVersion {get;...
Owner Property System.DirectoryServices.PropertyValueCollection Owner {get;set;}
Processor Property System.DirectoryServices.PropertyValueCollection Processor {get;set;}
ProcessorCount Property System.DirectoryServices.PropertyValueCollection ProcessorCount {get;set;}
Throwing in the PSBase option, I get much more when I run the gm.
$machine.PSBase | gm


TypeName: System.Management.Automation.PSMemberSet

Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
Close Method System.Void Close()
CommitChanges Method System.Void CommitChanges()
CopyTo Method adsi CopyTo(adsi newParent), adsi CopyTo(adsi newParent, string newName)
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
DeleteTree Method System.Void DeleteTree()
Dispose Method System.Void Dispose()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
Invoke Method System.Object Invoke(string methodName, Params System.Object[] args)
InvokeGet Method System.Object InvokeGet(string propertyName)
InvokeSet Method System.Void InvokeSet(string propertyName, Params System.Object[] args)
MoveTo Method System.Void MoveTo(adsi newParent), System.Void MoveTo(adsi newParent, string n...
RefreshCache Method System.Void RefreshCache(), System.Void RefreshCache(string[] propertyNames)
Rename Method System.Void Rename(string newName)
ToString Method string ToString()
AuthenticationType Property System.DirectoryServices.AuthenticationTypes AuthenticationType {get;set;}
Children Property System.DirectoryServices.DirectoryEntries Children {get;}
Container Property System.ComponentModel.IContainer Container {get;}
Guid Property System.Guid Guid {get;}
Name Property System.String Name {get;}
NativeGuid Property System.String NativeGuid {get;}
NativeObject Property System.Object NativeObject {get;}
ObjectSecurity Property System.DirectoryServices.ActiveDirectorySecurity ObjectSecurity {get;set;}
Options Property System.DirectoryServices.DirectoryEntryConfiguration Options {get;}
Parent Property System.DirectoryServices.DirectoryEntry Parent {get;}
Password Property System.String Password {set;}
Path Property System.String Path {get;set;}
Properties Property System.DirectoryServices.PropertyCollection Properties {get;}
SchemaClassName Property System.String SchemaClassName {get;}
SchemaEntry Property System.DirectoryServices.DirectoryEntry SchemaEntry {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
UsePropertyCache Property System.Boolean UsePropertyCache {get;set;}
Username Property System.String Username {get;set;}
As I began poking around I found lots of excellent information that would be good for something like the enumeration phase of a pen test, assuming you could get access to a machine via WinNT provider. It's also flat out useful to find out more about your machine. Here is a treasure trove of information:
($user.PSBase.children) | select * -First 1
UserFlags : {66051}
MaxStorage : {-1}
PasswordAge : {48034693}
PasswordExpired : {0}
LoginHours : {255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255}
FullName : {}
Description : {Built-in account for administering the computer/domain}
BadPasswordAttempts : {0}
LastLogin : {7/13/2009 10:53:58 PM}
HomeDirectory : {}
LoginScript : {}
Profile : {}
HomeDirDrive : {}
Parameters : {}
PrimaryGroupID : {513}
Name : {Administrator}
MinPasswordLength : {0}
MaxPasswordAge : {3628800}
MinPasswordAge : {0}
PasswordHistoryLength : {0}
AutoUnlockInterval : {1800}
LockoutObservationInterval : {1800}
MaxBadPasswordsAllowed : {0}
objectSid : {1 5 0 0 0 0 0 5 21 0 0 0 50 63 56 2 145 31 129 81 36 160 45 106 244 1 0 0}
AuthenticationType : Secure
Children : {}
Guid : {D83F1060-1E71-11CF-B1F3-02608C9E7553}
ObjectSecurity :
NativeGuid : {D83F1060-1E71-11CF-B1F3-02608C9E7553}
NativeObject : System.__ComObject
Parent : WinNT://WORKGROUP/MyMachine
Password :
Path : WinNT://WORKGROUP/MyMachine/Administrator
Properties : {UserFlags, MaxStorage, PasswordAge, PasswordExpired...}
SchemaClassName : User
SchemaEntry : System.DirectoryServices.DirectoryEntry
UsePropertyCache : True
Username :
Options :
Site :
Container :
If you don't think this tells you a lot about a given machine, I don't know what to tell you.

Pulling back from the hidden wealth of information just discovered and refocusing on the task at hand, I still needed to know how to add a new local user account. I dug up another, perfect script:
http://stackoverflow.com/questions/383390/create-local-user-with-powershell-windows-vista
which threw out a function:
function create-account ([string]$accountName = "testuser") {
$hostname = hostname
$comp = [adsi] "WinNT://$hostname"
$user = $comp.Create("User", $accountName)
$user.SetPassword("Password1")
$user.SetInfo()
}
Seeing snippets of references I had already looked at--Create, SetPassword, SetInfo--I figured I would go with this and just get things setup. After thinking it through, however, I decided to add a little functionality and write my own function, mainly to enable the specification of UserFlags. If you have never worked with the UserFlags enumeration it can be referenced here:
http://msdn.microsoft.com/en-us/library/Aa772300
Here is the main segment worth focusing on as outlined in the typedef for this enum:
typedef enum {
ADS_UF_SCRIPT = 1, // 0x1
ADS_UF_ACCOUNTDISABLE = 2, // 0x2
ADS_UF_HOMEDIR_REQUIRED = 8, // 0x8
ADS_UF_LOCKOUT = 16, // 0x10
ADS_UF_PASSWD_NOTREQD = 32, // 0x20
ADS_UF_PASSWD_CANT_CHANGE = 64, // 0x40
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128, // 0x80
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 256, // 0x100
ADS_UF_NORMAL_ACCOUNT = 512, // 0x200
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048, // 0x800
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096, // 0x1000
ADS_UF_SERVER_TRUST_ACCOUNT = 8192, // 0x2000
ADS_UF_DONT_EXPIRE_PASSWD = 65536, // 0x10000
ADS_UF_MNS_LOGON_ACCOUNT = 131072, // 0x20000
ADS_UF_SMARTCARD_REQUIRED = 262144, // 0x40000
ADS_UF_TRUSTED_FOR_DELEGATION = 524288, // 0x80000
ADS_UF_NOT_DELEGATED = 1048576, // 0x100000
ADS_UF_USE_DES_KEY_ONLY = 2097152, // 0x200000
ADS_UF_DONT_REQUIRE_PREAUTH = 4194304, // 0x400000
ADS_UF_PASSWORD_EXPIRED = 8388608, // 0x800000
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216 // 0x1000000
} ADS_USER_FLAG_ENUM;
This script can give you a taste of a few others ways to play with the UserFlags enum and the -bor operator if you want to be more precise in your settings:
http://poshcode.org/685
As noted in this post there is a little usage of the binary comparison operators. You can get more detail (plus some examples) by typing Get-Help about_comparison operators in your shell.

Once I had all this set up I arrived at this script:
function Add-LocalUser
{
param(
[Parameter(Mandatory = $true, Position = 1)]
[String]
$UserName,
[Parameter(Mandatory = $true, Position = 2)]
[String]
$Password,
[Parameter(Mandatory = $false, Position = 3)]
[Int32]
$UserFlags,
[Parameter(Mandatory = $false, Position = 4)]
[String]
$ComputerName = $env:COMPUTERNAME
)

$comp = [adsi] "WinNT://$ComputerName"
$user = $comp.Create("User", $UserName)
$user.SetPassword($Password)
if($UserFlags)
{
$user.UserFlags = $UserFlags
}
$user.SetInfo()
}
To use this function I do this:
Add-LocalUser User P@55w0RD (65536 + 64)
To add the user to a group, I can go back to the boiler plate code from the original Scripting Guys post and put this right where I need it.

Powershell - Function: Show-UserFlagsEnum

In the wake of my last post, I didn't really want to have to look up the UserFlags enum one more time. So, I created a simple function to display this text.
function Show-UserFlagsEnum
{
Write-Host "Explore this more at: http://msdn.microsoft.com/en-us/library/Aa772300`
ADS_UF_SCRIPT = 1, // 0x1`
ADS_UF_ACCOUNTDISABLE = 2, // 0x2`
ADS_UF_HOMEDIR_REQUIRED = 8, // 0x8`
ADS_UF_LOCKOUT = 16, // 0x10`
ADS_UF_PASSWD_NOTREQD = 32, // 0x20`
ADS_UF_PASSWD_CANT_CHANGE = 64, // 0x40`
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128, // 0x80`
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 256, // 0x100`
ADS_UF_NORMAL_ACCOUNT = 512, // 0x200`
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048, // 0x800`
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096, // 0x1000`
ADS_UF_SERVER_TRUST_ACCOUNT = 8192, // 0x2000`
ADS_UF_DONT_EXPIRE_PASSWD = 65536, // 0x10000`
ADS_UF_MNS_LOGON_ACCOUNT = 131072, // 0x20000`
ADS_UF_SMARTCARD_REQUIRED = 262144, // 0x40000`
ADS_UF_TRUSTED_FOR_DELEGATION = 524288, // 0x80000`
ADS_UF_NOT_DELEGATED = 1048576, // 0x100000`
ADS_UF_USE_DES_KEY_ONLY = 2097152, // 0x200000`
ADS_UF_DONT_REQUIRE_PREAUTH = 4194304, // 0x400000`
ADS_UF_PASSWORD_EXPIRED = 8388608, // 0x800000`
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216 // 0x1000000"
}
It can simply be called with Show-UserFlagsEnum. Save it off to your $profile.AllHostsAllUsers and make life easy the next time you want to reference some UserFlags value

Powershell - Get-EventLog Message Truncated

In efforts to automate some log monitoring/searching I turned to the Get-EventLog cmdlet. After getting it up and running I always have problems with the Message being truncated to a single line ended with an ellipsis. To get around this I Googled up this post:
http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_25029432.html
Although the main emphasis of the post was answered by a response emphasizing something else, I did find this nugget by Learnctx:
get-EventLog application -newest 2000 | where {$_.entryType -match "Error"} | where{$_.source -match "vmauthd"} | where{$_.timewritten -match $tdate} | format-table timewritten, message -wrap -autosize | Out-File -filepath c:\test.txt
From within this reply I got the command:
format-table timewritten, message -wrap -autosize
Applying this to my own command I then came up with this approach to see a specific log entry in a readable format:
$log = Get-EventLog -LogName Application
$log[0] | Format-Table -AutoSize -Wrap
To see all fields of the message try this:
$log[0] | Format-Table -AutoSize -Wrap
If you just select the Message field, it is automatically formatted:
$log[0].Message

Utility - Freecorder

A friend came to visit and was telling me about a song in the middle of a video stream she loved. I decided I'd go find a way to chop the portion of the stream she wanted. After I Googled up this post:
http://www.online-tech-tips.com/computer-tips/how-to-capture-save-record-or-download-streaming-audio-for-free/
I downloaded the tool and it worked pretty well. The only downside is that it installs on IE and Firefox at this point. About half the time I use Chrome, so, I was a little disappointed to see it wasn't an option

Video - Advanced .NET Debugging (John Robbins)

While digging around for some old materials I came across these three links on Channel 9:


Each of these links has the respective downloads (I went with the high quality wmv files):

  • http://ecn.channel9.msdn.com/o9/ch9/5/0/1/5/4/5/AdvancedNETDebugging1_2MB_ch9.wmv
  • http://ecn.channel9.msdn.com/o9/ch9/6/0/1/5/4/5/AdvancedNETDebugging2_2MB_ch9.wmv
  • http://ecn.channel9.msdn.com/o9/ch9/6/1/1/5/4/5/AdvancedNETDebugging3_2MB_ch9.wmv
These have been out here for a while, but, I pulled copies down just cause he's really good at guiding folks through debugging scenarios and I figure it would be worth having a copy just in case

Powershell - List Shares

Our datacenter had some power issues and I needed to quickly determine if our SAN had come back online. The quickest way I could come up with was a gwmi call to the remote machine. My first effort was on the Win32_LogicalDisk class:
gwmi -class Win32_LogicalDisk -computer 192.168.0.14 | select deviceid,drivetype,status,mediatype,access,volumename | ft -auto
If you are not familiar with this class, check out the definition at MSDN:
http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx
To get a better idea, as this didn't actually list shares but rather all drives, I used the Win32_Share class:
gwmi -class win32_share -computer 192.168.0.14 | select name,status
For more information on this class check out this page:
http://msdn.microsoft.com/en-us/library/aa394435(v=VS.85).aspx
Interestingly enough, I did a Get-Member to be sure I was picking all the info I needed. Since we are in a clustered environment, there is actually a Win32_ClusterShare class that derives from the Win32_Share class. If you run this command:
gwmi -class win32_share -computer 192.168.0.14 | select *
you can see all of the main fields
__GENUS
__CLASS
__SUPERCLASS
__DYNASTY
__RELPATH
__PROPERTY_COUNT
__DERIVATION
__SERVER
__NAMESPACE
__PATH
AccessMask
AllowMaximum
Caption
Description
InstallDate
MaximumAllowed
Name
Path
ServerName
Status
Type
Scope
Options
ClassPath
Properties
SystemProperties
Qualifiers
Site
Container
About the Win32_ClusterShare class:
http://support.microsoft.com/kb/971403
As noted by Radjin Sardjoe Missier in the Win32_Share community content section,
Suppose I have a server named SERVER01 that has a share named SHARE01.

To get this share object in powershell use the command:

[wmi]file://server01/root/cimv2:Win32_Share.Name='SHARE01'

This will also work for a Windows 2003 cluster where SERVER01 is the network name for a cluster group.

However, for a Windows 2008 cluster using CAP this will NOT work, because the Name property is now the UNC path to the share.

In such cases use:

[wmi]file://server01/root/cimv2:Win32_Share.Name='//SERVER01/SHARE01'

Actually for a cluster server the class name is Win32_ClusterShare which is a subclass of Win32_Share.

Powershell - Switch Parameters

I am trying to build a function that detects duplicates. To try and figure out how to add parameters which take no input I Googled up this post:
http://powershell.com/cs/blogs/tips/archive/2009/06/26/using-switch-parameters.aspx
So, to use this in my own function, I added these definitions (snippet shown purely for demo purposes):
function Find-Duplicates
{
param(
[string]$filePath,
[switch]$recurse
)

# Test filePath for proper syntax
if(!$filePath.EndsWith("\")
{
$filePath = $filePath + "\"
}

# Create command for invoking search. This can be dynamically added to before invocation to avoid a bunch of if/then and switch conditions in the code.
$command = Get-ChildItem -Path $filePath

# Add Date recurse switch
if($recurse)
{
$command = $command + " -recurse"
}

# Run actual search
Invoke-Command $command
}
When I call this function, I can simply call the function without the parameter:
Find-Duplicates -Path C:
In this case, the if will see $recurse as $false and not append the extra switch to the $command string we are building.

To run this switch I simply add the -recurse switch I define in my param list:
Find-Duplicates -Path C:\ -recurse
The fact that the switch is present sets $recurse = $true within the script so the $command variable then becomes:
Get-ChildItem -Path $path -Recurse
In effect the [switch] param allows for turning things on by merely adding the parameter to the call.

Powershell - Fillters in Functions

I am working with a function that needs a specific set of subprocesses run. I tried adding a nested function, but, Powershell didn't seem to take to that idea too well. Instead, I added a filter for checking MD5 hashes to my function. I got the MD5 snippet from Vadims Podams post:
http://www.vistax64.com/powershell/207882-get-md5-digest-powershell.html
which gave me:
function Hash-MD5 ($file) {
$hasher = [System.Security.Cryptography.MD5]::Create()
$inputStream = New-Object System.IO.StreamReader ($file)
$hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
$inputStream.Close()
$builder = New-Object System.Text.StringBuilder
$hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }
$output = New-Object PsObject
$output | Add-Member NoteProperty HashValue ([string]$builder.ToString())
$output.hashvalue
}
Modifying this I was able to pass in the pipelined object and get what I needed with some tweaking. The filter is bold text. I also bolded the use of the filter in the $command:

function Check-FileMD5
{
param(
[string]$path,
[switch]$recurse,
[switch]$fileName,
[switch]$hash
)

# Notify user script is running

Write-Host Searching for duplicates -ForegroundColor Green

# Filter for testing hashes

Filter MD5Hash
{
$hasher = [System.Security.Cryptography.MD5]::Create()
$inputStream = New-Object System.IO.StreamReader ($_.fullname)
$hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
$inputStream.Close()
$builder = New-Object System.Text.StringBuilder
$hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }
$output = New-Object PsObject
$output | Add-Member NoteProperty HashValue ([string]$builder.ToString())
$_.fullname + " :: " + $output.hashvalue
}


# Correct input string: add ending slash

if(!$path.EndsWith("\"))
{
$path = $path + "\"
}

# Build command

if($recurse)
{
$command = "Get-ChildItem -Path $path -recurse | Where {`$_.PSIsContainer -eq `$false} | select fullname"
}
else
{
$command = "Get-ChildItem -Path $path | Where {`$_.PSIsContainer -eq `$false} | select fullname"
}

if($hash)
{
$command = $command + " | MD5Hash"
}

Write-Host "The command to be processed is: $command"
Invoke-Expression $command
}
To use this function I type:
Check-FileMD5 -path C:\Data -hash -recurse

Powershell - Find Empty Folders in Directory Tree

I didn't create a whole lot here. I just used a Scripting Guys post and modified my search path. Here's the link:
http://technet.microsoft.com/en-us/library/ff730953.aspx
To get what I need I jump across a large set of folder trees:
dir \\192.168.0.2\a$\root\subname\*\storage | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetDirectories().Count -eq 0} | Select-Object FullName
This outputs a list of folders with no folders in them. If I wanted to tweak this to find folders without files, I wold use this pattern:
dir \\192.168.0.2\a$\root\subname\*\storage | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName
This way I don't have to research this again. Now, I can just go back to my blog for posterity's sake

ASP.NET 4.0 - Referencing App_Code Classes

I am working to learn how to properly use custom code from within an ASP.NET project. I added an App_Code directory to an empty project. Within the App_Code directory I created a folder called DLL and a file called DLL.cs. Looking back, I would have done it differently. The path [ProjectName].App_Code.DLL is pre-pended to the file name, DLL, in this case. So, when I reference the object in my project, CachingTest, it is fully written as CachingTest.App_Code.DLL.DLL. The second DLL in the name makes it a little more confusing. What I would more likely do is name the .cs file after the Object I am working with instead of the Folder class. I figured out how to access the code from this link:
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/pages/code.aspx
As it notes, you do need to add a
<%Import Namespace="CachingTest.App_Code.DLL">
declaration to be able to access the class. In my .aspx page, I included the previous Import statement as well as a simple code block:

<% CachingTest.App_Code.DLL.DLL test = new CachingTest.App_Code.DLL.DLL();
test.ResponseWrite();
%>
My code-behind class is super simple:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CachingTest.App_Code.DLL
{
public class DLL
{
public void ResponseWrite()
{
HttpContext.Current.Response.Write("Test");
}
}
}>
In my test page, I had to add some extra code for the Response.Write() snippet. To get this right, I had to look at XIII's post:
http://forums.asp.net/p/1019346/1377641.aspx
As he noted, you have to use:
use HttpContext.Current.Response.Write()

When you use a custom class to perform some actions you should get into the current context of the currrent execution/request of your handler, which is most likely a Page or HttpHandler.

ASP.NET 4.0 - Adding Typed DataSets

As with my post yesterday, I am working towards a real, enterprise-type application in terms of coding and file structure. After struggling with my approach based on the old ASP.NET article:
http://www.asp.net/data-access/tutorials/creating-a-data-access-layer-cs
When I tried adding the data in this case I kept getting errors when trying to reference the object in the DataAdapter provided by the .xsd. I posted on the ASP.NET forums:
http://forums.asp.net/t/1649988.aspx
and sandy060583 pointed me towards this article:
http://www.codeguru.com/csharp/sample_chapter/article.php/c13471
Now, so far I have tried these steps:
  1. Create an App_Code folder.
  2. Right click the application folder and add a new DataSet
  3. Within the DataSet Designer form I drag the table I want to type onto the form.
  4. Next, I have been going to the aspx.cs page and add code to reference the new DataSet.
So far I have found that the pattern for referencing these objects is as such. If I name a new DataSet CategoriesDataSet, then, the reference will look like this:
CategoriesDataSetTableAdapaters.CategoriesTableAdapter.
Taking this as the basis of my pattern I will start trying to reference my code this way:
[DataSetName]TableAdapters.[DataSetName]TableAdapter
Once I used this pattern, I was able to add code that actually worked:
// Add TableAdapter
CategoriesDataSetTableAdapters.CategoriesTableAdapter categoriesTableAdapter = new CategoriesDataSetTableAdapters.CategoriesTableAdapter();

// Fill DataTable
CategoriesDataSet.CategoriesDataTable categoriesDataTable = categoriesTableAdapter.GetData();

// Specify DataTable as GridView DataSource
GridView1.DataSource = categoriesDataTable;

// Bind DataTable to GridView
GridView1.DataBind();
Hopefully, I will be able to use them again in the future. I find every time I figure one of these things out, it changes the next time.

Rabu, 09 Februari 2011

Samsung RF510-S02 15.6-inch HD LED Laptop (Graphite Radiant Burst)

Samsung RF510, one of Samsung's new high-end consumer laptops. RF510, particularly has a beautiful industrial design, with Intel Core i7-720 processor, 4GB RAM, 640GB 7200rpm drive split into two partitions, NVIDIA GeForce GT 330M graphics, and a standard 1366 x 768 display HD LED 15.6-inch display.
It also features HDMI and a chargeable USB 3.0 port, meaning that you can charge a Zune, phone, or just about any other USB-compatible device even when the PC is off.

The RF510 is a prime example of that; thoughtful industrial design, great specs, and a reasonable price make it an excellent choice for anyone looking for a power 15" laptop.
You can get one identical to mine for $979 from amazon

Senin, 10 Januari 2011

griffin shows off crayola color studio HD for iPad

Take old world fun like drawing with crayons or magic markers and update it with the latest in high tech so it runs on the iPad and what do you get? All shades of awesome.
Grab an iMarker, launch the companion app, choose a active coloring landscape, and get your crayon on.
We checked it out live at CES 2011 so watch the video up top and let us know how busy this would keep your kids!
[Griffin]

Griffin shows off Crayola Color Studio HD for iPad - TiPb at CES 2011

Moonsoon introduces olcano flow, volcano blast to shift your tv to iphone ipad

Monsoon has announced two new boxes, Volkano Flow and Volkano Blast along with apps to let you transport (“sling”) your home TV to your iPhone or iPad.
Flow is $99 and is barebones slinging. Blast is $199 and added DVR, schedule recordings, web video like YouTube, and mobile video recording (you pick your mobile device and it will record a TV show specifically for that format). The iPad and iPhone apps are $9.99 and the Windows and Mac apps are free.
We got the live demo at CES 2011 so watch along and let us know if you’re interested in the new, cheap Volkanos.
[Monsoon]

Monsoon introduces Volkano Flow, Volkano blast to shift your TV to iPhone, iPad - TiPb at CES 2011

zagg`s zaggmate keyboard case for ipad 2011

ZAGG’s ZAGGmate is an aircraft-grade aluminum case for iPad… that also happens to convert to a full-on Bluetooth keyboard. It looks great — executive even — but for $99 it also provides road-warrier level text entry on top of protection. Check out our video live from CES 2011 and let us know — if you had any worries about iPad as a content creation, typing champion, would a case like this change your mind?
[ZAGG]

ZAGG's ZAGGmate keyboard case for iPad - TiPb at CES 2011

apple cutting out restocking fees and adding setup centers on january 2011


Apple Retail Stores are set to put an end to restocking fees starting Tuesday January 11, and will also be adding new setup areas for Macs, iPhones, and iPads.
Previously when returning a product to your Apple Retail Store you get hit with a 10 percent restocking fee but this will no longer be the case starting tomorrow. Of course the standard 14 day window will still apply for returns. The setup areas will be for those who need extra help getting started with their new Mac, iPhone, or iPad while leaving the Genius Bar clear to handle more technical support issues.
It seems fairly interesting that Apple chose Tuesday January 11 as the date to put an end to restocking fees and open their new setup areas, but maybe we will learn why tomorrow as Verizon holds their big press conference.
Either way do we really have to ask — are you going to be taking advantage of the no-restoking fees or setup area any time soon?

original AT&T iphone

iPhone introduction: 4 years later
While everyone waits for the big Verizon iPhone announcement tomorrow it’s a touch poetic to remember that the original Cingular/AT&T iPhone was announced on January 9, 2007 — almost four years ago to to the day.
Do you remember what smartphones were like before Steve Jobs took to the Macworld stage and finally revealed Apple’s wide screen iPod, internet communicator and revolutionary phone? Can you believe how far they’ve come since?
Let us know what you remember the most about the original iPhone introduction, what phone you were using at the time, and how in your opinion Apple has changed things (for good or for bad) since?
Video after the break!

daily tip : how to get a better Gmail on iphone

Daily Tip: How to get a better Gmail experience on iPhone
Big Google user and interested in getting a better Gmail experience on the iPhone? You can use IMAP or set up Gmail as Exchange via GoogleSync in the Mail app to cover the basics, but you won’t get stars and labels. You can use Gmail.com to get stars and labels, but you won’t get iPhone Contacts integration, attachment viewing, or easy access to multiple accounts. For that you have to get a little more… creative. We’ll show you how after the break.
[Thanks to The Keith Newman for this tip!]

Putting Gmail.com in an app

Gmail.com is a great web app and, of course, really nails the Gmail experience. Since it’s not a native app, however, it can’t do everything a native app can. Enter Mailroom [iTunes link]. It wraps the iPhone-optimized version of Gmail in a native App Store app, creating a hybrid that’s almost the best of both worlds. It does cost $2.99 but for hardcore Gmail users it’s well worth the price.

While it does provide iPhone Contacts integration, attachment viewing, multiple account support, offline mode, labels, stars, threaded conversations, badging of total unread and new message counts, and everything else you’d expect, it doesn’t — yet — support push notifications.

Getting Push Notifications

Google Mobile App

Google Mobile app [iTunes link] is free and does provide push notifications for your Gmail account (and Google Calendar), including the ability to turn off sound notifications during certain times (like when you’re sleeping).

You can’t make Mailroom your default mail client but you can see the badge on Google Mobile and then tap Mailroom instead.

Boxcar

Or you can use Boxcar [iTunes link] instead, also free and a push notification powerhouse, and set it to open Mailroom when you get a Gmail alert.

What would be better?

Sure, it’s not the most straightforward or elegant solution, but until Apple provides more functionality in iOS Mail (like flags and mapping stars to flags!), or Google makes a native iOS Gmail app, it can be just the compromise you need to get more productive on your iPhone.
If you have any questions or any other Gmail tips to share, leave them in the comments!
Tips of the day will range from beginner-level 101 to advanced-level ninjary. If you already know this tip, keep the link handy as a quick way to help a friend. If you have a tip of your own you’d like to suggest, add them to the comments or send them in to dailytips@tipb.com. (If it’s especially awesome and previously unknown to us, we’ll even give ya a reward…)

will the verizon iphone help fix the AT and T iphone

now that it looks all but certain the Verizon iPhone will be announced tomorrow, one of the questions that arrises is will users switching from AT&T help take the load off and create a better level of service for everyone? First, a personal anecdote: I left Montreal to fly to CES 2011 last Tuesday. In Montreal the iPhone is fast, like HSPA 7.2 fast, with nary a dropped call and lost network signal, and a battery life that lasts as long as Apple’s TV commercial suggests.
I switched planes in Charlotte and began to roam on AT&T. My iPhone 4 showed full bars but I kept getting a popup saying there was no network connection. That means the tower was broadcasting but there was no backhaul behind it. Like if your home Wi-Fi router is fine but your broadband ISP is down — lots of radio, no internet.

I asked an iPhone user next to me if he could get online. He couldn’t. No one at our gate or on our plane could. Luckily for me roaming iPhones can jump on any network so I switched to T-Mobile EDGE and was fine. None of the Americans could do that, however, so they just sat and cursed, the way a lot of Americans have been cursing for years.
Las Vegas was no better. You’d think CES and the thousands of iPhones that descend on it would just shred AT&T’s network but locals said the signal was never great. They blamed the casinos. (And maybe so, T-Mobile didn’t work in some buildings either.)
Of course, when there’s weak signal, the iPhone ratchets up the radio trying to latch onto it and that means the battery drains. And drains. Remember I said my battery lasts a long time in Canada? I could watch it drop on AT&T while I ate breakfast.
There’s likely a number of factors that create this perfect storm of hurt in some areas (because — and I need to stress this — AT&T is fine for a lot of people in a lot of places with a lot of different smartphones).
  • AT&T should have spent more building out their network sooner and faster.
  • The iPhone’s radio chipset never seems to have worked as well on AT&T as it did on international carriers.
  • AT&T and Apple should have made sure the technology in the phones and towers was optimized to give their customers the best experience possible.
  • And the amount of iPhone users hitting AT&T towers in high density areas was just paralyzing and needed either more towers or they should have broken exclusivity earlier to help spread the load around.
Again, the customers should have come first.
So now that iPhone is finally poised to go to Verizon there will be a network behind it that can serve more users with less towers more reliably (albeit with less features, like no simultaneous voice and data, and slower speeds). You’ll have a new CDMA chipset hitting different tower technology that might just work better. And you’ll have a segment of AT&T iPhone users switching to Verizon, finally spreading the load around. (Not as much as if T-Mobile and Sprint also got the iPhone and made the iPhone truly free in the land of the free, but that’s another rant.)
We’re running a poll asking our readers how many will stay with AT&T and how many will switch to Verizon and so far it looks like a big portion are at least considering the switch, and an even bigger portion is welcoming their departure in hopes it de-congests their own service.
A new radio and new radio software stack on a new carrier with what’s likely to be a ton of new iPhone users hitting all those Verizon towers — it remains to be seen how well Big Red’s Map holds up. (They seem to think it’ll do well enough to keep unlimited plans on the table — at least for now.) Whether it does brilliantly or struggles like AT&T’s has under the weight of iPhone, at least for the first time a US network won’t be struggling alone.
Could that just be enough to take the straw off AT&T’s severely aching back?

Minggu, 09 Januari 2011

i phone no longer exclusive, still locked system

With the expected announcement and launch on Verizon this month, AT&T exclusivity will be over and the iPhone will finally be available on another US carrier — but it will still be locked.
Unlike most other countries where iPhone is available on multiple carriers, you won’t be able to go to an Apple store and pay full price for an unlocked iPhone you can use on any network — or any carrier around the world with a simple SIM swap. Verizon, being a CDMA rather than GSM carrier doesn’t use SIMs.
Instead US customers will have the choice between two locked iPhones — locked to AT&T or locked to Verizon, unable to move between the two, and not even able to officially move to the other GSM and CDMA carriers in the US, T-Mobile and Sprint. While we don’t know for certain, in all likelihood you won’t be able to call your carrier and get your iPhone unlocked, you won’t even be able to pay them to unlock it.
That means if you’re currently an AT&T iPhone user and you want to move to Verizon you have to buy a new Verizon iPhone. You can’t take it with you. And if you get a Verizon iPhone and decide life on AT&T really was better, there’s no bringing your new iPhone back.
Will there ever be a time when an American can walk into an Apple Store and buy an unlocked iPhone, capable of working on any carrier in the US, just like in most of the rest of the world? Because come this time next month the iPhone in the US — land of the free — will still be locked. It’ll just be locked to two carriers instead of one.

Sabtu, 08 Januari 2011

iPhone 3G Multi-touch

I finished writing a driver for the Zephyr2 on the iPhone. It's the same multi-touch solution that Apple has used starting from the first generation iPod touch and up to and including the iPad.

Now, of course this shouldn't be construed as a promise to support the iPad eventually, but this multi-touch driver is definitely a concrete milestone that is important for pretty much all of Apple's mobile Internet devices.

More immediately, this is pretty much the sole remaining blocking issue on the first-gen iPod touch and one of the two major issues on the iPhone 3G. The other issue on the iPhone 3G is baseband SPI. I'm wondering if we can get away with just using the debug uart to make calls (if we don't care about having a fast 3G data connection yet).

Android running on iPhone!

I've been working on this quietly in the background. Sorry about the initial video quality, but YouTube promises that the quality will get better as the video gets processed more. The back part of the version I uploaded to Vimeo was cut off.



I think that says it all, really. Donations via paypal to planetbeing at gmail.com. If you'd like to help, come join #iphonelinux on irc.osx86.hu.

Thanks to CPICH for reversing support, harmn1, posixninja, jean, marcan and saurik for patches, and last but not least, TheSeven for his work on the FTL.

Pre-built images and sources at http://graphite.sandslott.org:4080/pub/idroid/idroid-release-0.1a.tar.bz. Read the README. For generic openiboot instructions, there's plenty now that you can search for.

It should be pretty simple to port forward to the iPhone 3G. The 3GS will take more work. Hopefully with all this groundwork laid out, we can make Android a real alternative or supplement for iPhone users. Maybe we can finally get Flash. ;)

Jumat, 07 Januari 2011

apple i phone wallpaper





 
Powered by Blogger