How To Dynamically Sort a List<T> During the SortCommand Of a Telerik RadGrid



TODO:

Have you ever wanted to catch the Sort Event of a Telerik RadGrid, and sort your datasource?   This comes in handy if you are using the rows in the grid as a 1 to 1 map with items in the datasource.  This saves you from needing to worry about working with the rows and columns of a grid, but instead you can work with the List of Objects, and simply ReBin().

 

SOLUTION:

protected voidrgdMyGrid_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
{  
    //check the sort order.  if it is descending, then we need to order list that way, otherwise use default of ascending.
    Func<MyObject, string> orderByColumn =null;
    
    //Figure out which sort column
    switch (e.SortExpression)
    {
        case "FirstName":
            orderByColumn = s => s.FirstName;
            break;
        case "LastName":
            orderByColumn = s => s.LastName;
            break;
        case "Telephone":
            orderByColumn = s => s.Telephone;
            break;
    }
    
    //now check the sort order, and sort accordingly
    if (e.NewSortOrder == GridSortOrder.Descending)
    {
        myDataSource = myDataSource.OrderByDescending(orderByColumn).ToList();
    }
    else
    {
        myDataSource = myDataSource.OrderBy(orderByColumn).ToList();
    }
    rgdMyGrid.DataSource = null;
    rgdMyGrid.Rebind();
}

 

NOTES:

MyDataSource is a List<MyObject>.  I was using the datasource for the grid and had to keep them in sync, because sorting the grid did not by default sort the datasource.  You also need to sort the datasource on insert, update, and delete of an item in the RadGrid, if a sort column is selected.

Possible Fix For A Sluggish iPad



TODO:

Your iPad is slow, you click on items and it just outlines them.  If you double or triple click an item, it may select it or it may not.

 

SOLUTION:

You may have an iPad that is in Voice Over mode.  In my case, I had the volume down the whole way, and was not familiar with what Voice Over looked like when activated.  IF you triple click the home button, it should toggle the iPad out of Voice Over mode.  That setting is controlled in the Settings area.

 

NOTES:

There are no notes on this topic

How To Clean Up "Other" Files On iPhone



TODO:

Have you ever noticed a large amount of data in the 'Other' area in iTunes?  It is yellow, and in my case was 3gb+

 

SOLUTION:

To fix, follow the instructions on this link

 I have tried this solution and it worked perfectly!

 

NOTES:

There are no notes on this topic.

How To Fix "Cannot detach a suspect or recovery pending database. It must be repaired or dropped." Error



TODO:

Have you ever received the error "Cannot detach a suspect or recovery pending database. It must be repaired or dropped." when trying to detach a database that is suspect?

 

SOLUTION:

ALTER DATABASE MyDB SET EMERGENCY;
GO
ALTER DATABASE MyDB set single_user
GO
DBCC CHECKDB (MyDB, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
GO
ALTER DATABASE MyDB set multi_user
GO

 

NOTES:

Once that is done, you can then detach, and attach, or just bring online.

How To Sort List Of Objects In .Net



TODO:

You have a list of objects (List<T>), let's just say List<Dog> for this example.  You want to sort them by a property called "Breed".  This example will show you just how to do that.

 

SOLUTION:

List myDogList = myDogList.OrderBy(d => d.Breed).ToList();
//or
List myDogList = myDogList.OrderByDescending(d => d.Breed).ToList();

 

NOTES:

Your list of dogs will now be sorted by Breed. 

*****Note that the default sort order is ascending.

How To Set Modified By User Back To The Original User When Impersonating A User In An Event Receiver



TODO:

You impersonate a user in an event receiver, and the result of calling Update() on the list item means that the "Modified By" user is that of the impersonated account, and not the original user that was logged into the site.  The solution is pretty simple, just use the code below to set that user back to the original user.

 

SOLUTION:

private void ApplyPermissions(SPItemEventProperties properties)
{
    string debugMessage = string.Empty;
    Guid webId = properties.ListItem.Web.ID;
    Guid siteId = properties.SiteId;
    SPUserToken sysToken = null;
    SPUser currentUser = null;

    try
    {
        currentUser = properties.Web.CurrentUser;

        //open site, and get elevated user
        using (SPSite site = new SPSite(siteId))
        {
            //use our site collection
            using (SPWeb myWeb = site.OpenWeb(webId))
            {
                sysToken = myWeb.AllUsers["i:0#.w|mydomain\\impusr"].UserToken;
            }
        }

        bool allowUnsafeUpdates = false;

        //open site with elevated user
        using (SPSite site = new SPSite(properties.SiteId, sysToken))
        {
            //get the web
            using (SPWeb myWeb = site.OpenWeb(properties.ListItem.Web.ID))
            {
                try
                {
                    allowUnsafeUpdates = myWeb.AllowUnsafeUpdates;  //save unsafe update setting
                    myWeb.AllowUnsafeUpdates = true;  //allow unsafe updates for now

                    SPListItem elevatedListItem = null;
                    elevatedListItem = myWeb.Lists[properties.ListId].Items[properties.ListItem.UniqueId];  //get elevated list item
                            
                    //DO ELEVATED ACTIONS HERE 

                    base.EventFiringEnabled = false;
                    elevatedListItem["Editor"] = currentUser; //set current user to editor and author  
                    elevatedListItem["Author"] = currentUser; 
                    elevatedListItem.Update(); //update the item                 
                    base.EventFiringEnabled = true;
                }
                catch (Exception x)
                {
                    throw x;
                }
                finally
                {
                    myWeb.AllowUnsafeUpdates = allowUnsafeUpdates;  //put back original setting    
                }
            }//using web   
        }//using site
    }
    catch (Exception x)
    {
        properties.ErrorMessage = x.ToString();
    }
}

 

 

NOTES:

This code ran in an ItemAdded and ItemUpdated Event Receiver

How To Attach A SQL Server Database MDF File Without A Log File



TODO:

Recently I had a corrupt log file, and my database was continuously 'Suspect'.  Since this was a test database, I did not care about my corrupt .ldf file.  Therefore, I simply wanted to attach my .mdf file and let it create a new .ldf file.  The SQL below will do just that.

 

SOLUTION:

CREATE DATABASE myDatabase ON
( FILENAME = N'G:\DATA\myDatabase.mdf')
FOR ATTACH
GO

 

NOTES:

This method works when there is only one log file and it is missing.

IF there is more than 1 log file, use 'FOR ATTACH_REBUILD_LOG' rather than 'FOR ATTACH'

 

How To Get The Selected Value Of a RadioButtonList In JQuery



TODO:

Have you ever wanted to get the selected value of a RadioButtonList using JQuery?  You can do it via CssClass, but in this example, I want to target a particular control.

 

SOLUTION:

//handle nothing being checked
if ($("#<%= rblMyRadioList.ClientID %> input:checked").val() == null) {
     return;
}

var selectedValue = $("#<%= rblMyRadioList.ClientID %> input:checked").val().toUpperCase();

 

NOTES:

There are no notes on this topic.

How to Find And Rebuild Fragmented Indexes In SQL Server Using T-SQL



TODO:

Have you ever wanted to get badly fragmented indexes, and rebuild them using T-SQL?

 

SOLUTION:

CREATE procedure [dbo].[sp_GetIndexFragmentation]
AS

-- Declare variables
SET NOCOUNT ON;
DECLARE @tablename VARCHAR(128);
DECLARE @execstr   VARCHAR(255);
DECLARE @objectid  INT;
DECLARE @indexid   INT;
DECLARE @frag      decimal;
DECLARE @maxfrag   decimal;

-- Decide on the maximum fragmentation to allow for.
SELECT @maxfrag = 30.0;

-- Declare a cursor.
DECLARE tables CURSOR FOR
   SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))
	+'.'+CAST(TABLE_NAME AS VARCHAR(100))
           AS Table_Name
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = 'BASE TABLE';

-- Create the table.
CREATE TABLE #fraglist (
   ObjectName CHAR(255),
   ObjectId INT,
   IndexName CHAR(255),
   IndexId INT,
   Lvl INT,
   CountPages INT,
   CountRows INT,
   MinRecSize INT,
   MaxRecSize INT,
   AvgRecSize INT,
   ForRecCount INT,
   Extents INT,
   ExtentSwitches INT,
   AvgFreeBytes INT,
   AvgPageDensity INT,
   ScanDensity decimal,
   BestCount INT,
   ActualCount INT,
   LogicalFrag decimal,
   ExtentFrag decimal);

-- Open the cursor.
OPEN tables;

-- Loop through all the tables in the database.
FETCH NEXT
   FROM tables
   INTO @tablename;

WHILE @@FETCH_STATUS = 0
BEGIN;
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS');
   FETCH NEXT
      FROM tables
      INTO @tablename;
END;

-- Close and deallocate the cursor.
CLOSE tables;
DEALLOCATE tables;

-- Declare the cursor for the list of indexes to be defragged.
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag
   FROM #fraglist
   WHERE LogicalFrag >= @maxfrag
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0;

-- Open the cursor.
OPEN indexes;

-- Loop through the indexes.
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag;

WHILE @@FETCH_STATUS = 0
BEGIN;
   PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@tablename) + ',
      ' + RTRIM(@indexid) + ') - fragmentation currently '
       + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%';
   SELECT @execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@objectid) + ',
       ' + RTRIM(@indexid) + ')';

--UNCOMMENT LINE BELOW TO ACTUALLY DEFRAG   
--EXEC (@execstr);

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag;
END;

-- Close and deallocate the cursor.
CLOSE indexes;
DEALLOCATE indexes;

-- Delete the temporary table.
DROP TABLE #fraglist;

 

NOTES:

There are no notes on this topic

How To Shrink Database File Using DBCC Shrinkfile



TODO:

Have you ever wanted to shrink a database or log using DBCC Shrinkfile?

 

SOLUTION:

DBCC SHRINKFILE(DataOrLogFile, 1)

 

NOTES:

There are no notes on this topic