Blog Archives

asp .net repeater itemcommand command name common repeater control item operations

This is only one small snippet illustrating some functionality. I will add to this blog from my previous usage with Repeater control over time or per request.

In many deployments, I prefer to use Repeater or ListView rather than Grids. The code pattern is the same, but the output is slightly different as well as some of the inherent features/functionality.

Notice the example below simulates table output similar to a Grid, or it may also be used for non-table type of output. Repeater is therefore IMO more adaptable to different needs, and allows more re-usability code patterns across projects.

page side:

<asp:Repeater ID="rptRobotsInFactories" runat="server" OnItemCommand="rptRobotsInFactories_ItemCommand">
        <HeaderTemplate>
<table>
<tr>
<td>factory name</td>
<td>robot name</td>
<td>factory location</td>
<td>manufacture date</td>
<td colspan="2">commands</td>
</tr>
   </HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("factoryname")%>
<asp:TextBox ID="tbRobotName" runat="server" Text='<%# Eval("robotname")%>'></asp:TextBox>
</td>
<td>
<%# Eval("factorylocation")%>
</td>
<td>
<%# Eval("manufacturedate")%>
</td>
<td>
<asp:LinkButton ID="lbtnRename" runat="server"> CommandName="rename" CommandArgument='<%# Eval("robotname")%>'>rename</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lbtnDeelte" runat="server"> CommandName="delete" CommandArgument="">delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
        </HeaderTemplate>
<FooterTemplate>
<!-- insert pager here if you like-->
        </table>
        </FooterTemplate>
		</asp:Repeater>

code behind:

//you can also intercept item databind as i've listed in another previous article on nested repeaters

 protected void rptRobotsInFactories_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "rename")
        {
            string newname = ((TextBox)rptRobotsInFactories.Items[e.Item.ItemIndex].FindControl("tbFileName")).Text;
            //string newname = ((TextBox)e.Item.FindControl("tbFileName")).Text; //equal to the above
            //string index = (string)e.CommandArgument; //useful to pass in index values also. can split the values passed in or pass in class obj
            //var rif = ((List<robotinfactory>)rptRobotsInFactories.DataSource)[e.Item.ItemIndex];
//var rif = Session_RobotsInFactories().Select(r=>r.id==Convert.ToInt32(e.CommandArgument)); //compare to using viewstate/page repeater above
            string oldname = (string)e.CommandArgument;
            if ((newname.ToLower().Trim().Replace(" ","") != "") && (newname!=oldname))
            {
//dowork_rename(oldname,newname);
            }
        }
else if (e.CommandName=="delete") {
            robotinfactory rif = ((List<robotinfactory>)rptRobotsInFactories.DataSource)[e.Item.ItemIndex];
//dowork_delete(rif.id);
}
    }

//added below funcs for clarity
public class robotinfactory() {
public string factoryname {get;set;}
public string robotname {get;set;}
public string factorylocation {get;set;}
public string manufacturedate {get;set;}
}

protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//these would normally load from your LINQ dbml SP, view, select statement, stored procedure etc
var rifs = new List<robotinfactory>();

rifs.Add(new rif {
factoryname="a",
robotname="bob",
factorylocation="florida",
manufacturedate="7/1/2013"
});

rifs.Add(new rif {
factoryname="b",
robotname="sam",
factorylocation="not florida",
manufacturedate="7/4/2013"
});

rptRobotsInFactories.DataSource = rifs;
rptRobotsInFactories.DataBind();
}
}

directory info get files show directories C# .Net

There is sometimes a misunderstanding between a “file” and a “folder” in filesystems. In C# .Net the following is often used to list all “files” in a folder.

DirectoryInfo di = new DirectoryInfo("yourpath");

foreach (FileInfo fi in di.GetFiles()) {
//do work
}

However, even though you can specify to search containing subdirectories, the above function will not inherently list folders. If you are looking for the equivalent to “dir” or “ls”, instead use “GetFileSystemInfos()”.

            DirectoryInfo di = new DirectoryInfo("yourpath");
		
//note the difference here with getfilesysteminfos
		foreach (dynamic d in di.GetFileSystemInfos()) {
}

Note the usage of dynamic in the above example compared to the first example. This avoids any potential issues with inheritance and choosing the right class for your temp iterator variable for unboxing etc.

Keep Batch File Open to enter more commands

Typically the solution you will see to this question upon googling is to add “pause” to the end of your batch file.

This will keep the batch open, but it will not allow you to enter additional commands and after hitting a key will close the window immediately.

Alternatively, if you would like to keep the window open, such as creating a shortcut to a command line app, you can use cmd.exe /K.

G:\PathToMyCommandLineExeApp
G:
MyApp.exe /?
cmd.exe /K cmd.exe

Place the above code snippet into batch file of your choosing, such as start menu folder, and upon launch it will not change into the directory and path where your command line app is located, execute it displaying it’s parameters (/? is app specific) and then run cmd.exe with \K option which allows the window to stay open per MSDN (see reference below).

Enjoy.

References
MSDN, http://support.microsoft.com/kb/830473

Reset Password from Command Prompt in Server 2008

For a developer or IT admin working in Windows Server 2008 environment, you may have noticed ctrl+alt+del does not work over remote connection and you can no longer change your password from control panel.

The best solution to this in my opinion, that will likely work far into the future, is the command line.

Also keep in mind you are a server admin and disable much functionality for your remote users, sometimes these permissions don’t always apply to command line variants and the latter can be used for privilege escalation in the event of a workstation or user profile compromise.

net user user_name * /domain

net user user_name  new_password

ex.
net user Bob 12bdir5$

References
Microsoft Support, “How to Change User Password at Command Prompt”,

MSSQL Quick Reference

Snippets below have been condensed from their original sources for brevity. See references for original articles.

Great reference on joins: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
Visual_SQL_JOINS_V2

Show all tables in specific database: (MSSQL equivalent of MySql “show tables”)

select name from <database name>..sysobjects where xtype = 'U'

Insert into:

INSERT INTO MusicArtists (FirstName, LastName, Instrument)
VALUES ('Bobby', 'Lee', 'fiddle');

INSERT INTO Duos (Member1) 
    SELECT FirstName + ' ' + LastName FROM MusicArtists;

INSERT INTO Duos (Member1) 
    SELECT FirstName + ' ' + LastName FROM MusicArtists 
    WHERE MusicianID > 3;

INSERT INTO Residents (Name, Occupation)
    SELECT Name, Occupation FROM Immigration 
    WHERE Residency = 'granted';

INSERT INTO Insurance (Name) 
    SELECT Employee.Username FROM Employee 
    INNER JOIN Project ON Employee.EmployeeID = Project.EmployeeID 
    WHERE Project.ProjectName = 'Hardwork';

Insert if not exists:

IF NOT EXISTS (SELECT * FROM dbo.Applications WHERE Username = Tom ANDApplication = Calculator) BEGIN
 INSERT INTO dbo.Applications 
 (Date, Username, Application, Version) 
 VALUES
 ('3/10/2009', 'Tom', 'Calculator', '2.0') 
END

Trigger Syntax Structure:

CREATE TRIGGER trigger_name 
ON { table | view } 
[ WITH ENCRYPTION ] 
{ 
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ WITH APPEND ] 
[ NOT FOR REPLICATION ] 
AS 
[ { IF UPDATE ( column ) 
[ { AND | OR } UPDATE ( column ) ] 
[ ...n ] 
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask ) 
{ comparison_operator } column_bitmask [ ...n ] 
} ] 
sql_statement [ ...n ] 
} 
} 

Basic If, Then , Else and case:

--longer
create proc sp_generic (@cust int, @type int)
if @type = 1
 select * from customer where customerid = @cust
else
 Select * from deleted_customers where customerid = @cust

--shorter
create proc sp_generic (@deptid int )
select * from employees where departmentid = case when @dept >0 then @dept else departmentid end
order by departmentid

Insert Trigger:

CREATE TRIGGER trig_addAuthor 

ON authors 

FOR INSERT 

AS

-- Get the first and last name of new author 

DECLARE @newName VARCHAR(100) 

SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted)

-- Print the name of the new author 

PRINT 'New author "' + @newName + '" added.'

Update Trigger:

USE AdventureWorks2008R2;
GO
IF EXISTS (SELECT name FROM sys.objects
      WHERE name = 'reminder' AND type = 'TR')
   DROP TRIGGER Person.reminder;
GO
CREATE TRIGGER reminder
ON Person.Address
AFTER UPDATE 
AS 
IF ( UPDATE (StateProvinceID) OR UPDATE (PostalCode) )
BEGIN
RAISERROR (50009, 16, 10)
END;
GO
-- Test the trigger.
UPDATE Person.Address
SET PostalCode = 99999
WHERE PostalCode = '12345';
GO

Get and/or compare today’s date:

convert(varchar,CURRENT_TIMESTAMP,101)
convert(varchar(12),getdate(),101)

Insert or Update with case statements:

USE [mydatabasename]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_update_manufacturedrobots_count]
	@mfgid int,
	@robotid int,
	@paintbotcount int=null,
	@drillbotcount int=null,
	@hammerbotcount int=null
AS
BEGIN

	SET NOCOUNT ON;

declare @id int
select @id = id from manufacturedrobots where mfgid=@mfgid and robotid=@robotid
if @id is not null
update manufacturedrobots set 
paintbotcount=case
when @paintbotcount is null then paintbotcount 
else @paintbotcount end, 
favorite=case
when @drillbotcount is null then drillbotcount 
else @drillbotcount end, 
checkedin=case
when @hammerbotcount is null then hammerbotcount 
else @hammerbotcount end
where id=@id
else
insert into manufacturedrobots (paintbotcount,drillbotcount,hammerbotcount) values  (@paintbotcount,@drillbotcount,@hammerbotcount)

END

Cursor:

USE AdventureWorks
GO
DECLARE @ProductID INT
DECLARE @getProductID CURSOR
SET @getProductID = CURSOR FOR
SELECT ProductID
FROM Production.Product
OPEN @getProductID
FETCH NEXT
FROM @getProductID INTO @ProductID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @ProductID
FETCH NEXT
FROM @getProductID INTO @ProductID
END
CLOSE @getProductID
DEALLOCATE @getProductID
GO

References:
MSDN, http://msdn.microsoft.com/en-us/library/ms187326.aspx
DevGuru, http://www.devguru.com/technologies/t-sql/7124.asp
DevArticleshttp://www.devarticles.com/c/a/SQL-Server/Using-Triggers-In-MS-SQL-Server/1/
MSDN, “How to debug stored procedures in Visual Studio .NET”, http://support.microsoft.com/kb/316549
CodeGuru, http://www.codeguru.com/forum/showthread.php?t=473102
DaniWeb, http://www.daniweb.com/forums/thread43719.html
SqlAuthority, http://blog.sqlauthority.com/2008/03/05/sql-server-simple-example-of-cursor-sample-cursor-part-2/