Wednesday, October 9, 2013

.NET Regex - using $ and \r\n

Symptom:
I have a list of values in a textbox...

apple
banana
cherry
donut

In a textbox it looks like this:

TextBox1.Text = "apple\r\nbanana\r\ncherry\r\ndonut\r\n";

Let's parse through the list using a pattern and do a replace...

Then I'll do a replace...

TextBox1.Text = Regex.Replace(TextBox1.Text,  "^(.*)$" , "I like to put $1 on my plate.\r\n", RegexOptions.Multiline);

I would expect to see this:

I like to put apple on my plate.
I like to put banana on my plate.
I like to put cherry on my plate.
I like to put donut on my plate.

Instead, I see this:

I like to put apple
 on my plate.
I like to put banana
 on my plate.
I like to put cherry
 on my plate.
I like to put donut
 on my plate.

It turns out that $ is matching \n, but not \r.

Solution:

Change to this and it worked as expected:

TextBox1.Text = Regex.Replace(TextBox1.Text,  "^(.*)\r\n" , "I like to put $1 on my plate.\r\n", RegexOptions.Multiline);

Thursday, January 24, 2013

UpdatePanel doesn't like the ViewState being tampered with!


Symptom:
Previous instances of RadAjaxPanel were replaced with UpdatePanel.  Suddenly, controls within that page no longer postback.

Sample Code:
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
    <ContentTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
    </ContentTemplate>
</asp:UpdatePanel>

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text = DateTime.Now.ToString();
}

protected void Button2_Click(object sender, EventArgs e)
{
Button2.Text = DateTime.Now.ToString();
}

When alternating clicks between Button1 and Button2, I would expect that the clicked button would update with the current time.  Instead, the button values were clearing.


Solution:
It turns out this was specific to a certain page.  On a normal page, it worked fine.  On the page with these symptoms, I discovered it was related to a solution that implimented due to a large ViewState.  I was overriding SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium and that was causing the UpdatePanel to fail when saving the ViewState information to the Cache.

Can't publish files in Visual Studio 2012


Symptom: 
When publishing files to a local drive with Visual Studio 2012, there seems to be no files in the destination directory.

Additional Symptoms:
- The My Project folder has some read-only .pubxml files that contain settings for publishing.  Deleting them seems to make deploying work again.
- After a Get Latest from TFS, my previously successful Publish settings are overridden with another team member's settings.

Solution:
When publishing a project, give the profile name something unique like your own name.  This will make a seperate .pubxml file with your settings.  Other team members using unique profiles with their own names should no longer affect your settings.  When they change their profile settings, their .pubxml file will be checked out and updated accordingly.

Friday, November 23, 2012

Not receiving MMS w/ ting on my Samsung SIII

Symptom:  People did not receive pictures we sent and we did not receive pictures that they sent.

Environment:
Pam using a Samsung Galaxy SIII, stock rom, rooted, but without the latest patch.
James using a Samsung Galaxy SIII, CM10 rom, using cm-10-20121118-NIGHTLY

Solution for Pam's phone:

  • dial ##DATA#
  • select Edit
  • enter MSL (obtain from ting, or go to the website, find Account, Device Settings, Select the phone number, and the MSL is under it)
  • select Others
  • select MMSC URL
  • change from http://mms.sprintpcs.com to http://mms.plspictures.com
  • save and reboot


Solution for James's phone:


  • It seems there was no obvious way to natively edit the MMS setting with CM10.  Various sources indicated I needed to edit a file.  To make things easier, I installed DropBear SSH server.
    https://play.google.com/store/apps/details?id=me.shkschneider.dropbearserver
  • SSH in, then remount the file system:
    • root@android:/ # cd /system/etc
    • root@android:/system/etc # mount -o rw,remount /system
  • Using vi, I altered /system/etc/apns-conf.xml to replace references for mms.sprintpcs.com to be mms.plspictures.com
  • Rebooted, MMS now works.  Reboot may not have been necessary even.



Wednesday, October 3, 2012

Getting the Repeater row index from the LinkButton


This is one I am posting for my own reference so I can find it easier...  When Clicking a LinkButton in a Repeater, I needed the index available to modify a cached DataTable.

Situation:  Getting the Repeater row index from the LinkButton

Solution:

        LinkButton lnkButton = sender as LinkButton;
        int RepeaterItemIndex = ((RepeaterItem)lnkButton.NamingContainer).ItemIndex;

Credit to kaushalparik27 at http://forums.asp.net/t/1333400.aspx/1

Tuesday, October 2, 2012

Scroll after postback


Situation: Button inside of a GridView fires the Command event and needs to scroll to the bottom of the page.

Solution:  Use an anchor tag, then use ClientScript.RegisterStartupScript on the end of the event method to scroll to it.

Credit goes to http://forums.asp.net/t/1311972.aspx/1

Monday, August 13, 2012

SQL string splitter


I really prefer to give credit for these types of things, but I don't remember where I found it :(

Basic syntax... select dbo.FN_STRING_HELPER_SPLIT('My name is James', ' ', 4) will return 'James'



CREATE FUNCTION [dbo].FN_STRING_HELPER_SPLIT
(
  @strToSplit as varchar(4000),
  @delimiter as varchar(50),
  @columnToReturn as int
)
RETURNS varchar(25)
AS
BEGIN
  -- Declartion of the return variable
  DECLARE @i as int
  DECLARE @occurrences as int
  DECLARE @delimiterIndex as int
  DECLARE @actSplitValue as varchar(4000)
 
  -- T-SQL statements to compute the return value here
  SET @i = 1
  SET @delimiterIndex = 1
 
  WHILE @i <= @columnToReturn
  BEGIN
    SET @delimiterIndex = CHARINDEX(@delimiter, @strToSplit)
    -- if not found end while
    SET @actSplitValue = @strToSplit
    IF @delimiterIndex = 0 BEGIN
      BREAK
    END
    SET @actSplitValue = LEFT(@strToSplit, @delimiterIndex - 1)
    -- SUBSTRING(string, von, bis)
    SET @strToSplit = SUBSTRING(@strToSplit ,@delimiterIndex +1, LEN(@strToSplit)- @delimiterIndex)
    SET @i = @i + 1
  END
  -- the result of the function
  RETURN @actSplitValue
END

Friday, May 25, 2012

Rendering a UserControl as string



I was given the task of creating an HTML based email that sent the contents of a webform.  This is where I explored the possibility of rendering an independant usercontrol into a string.


I did some searching and came across code like this:

Page pageHolder = new Page();

PrintVersion pv1 = (PrintVersion)pageHolder.LoadControl("PrintVersion.ascx");

pv1.BindData();

pageHolder.Controls.Add(pv1);


StringWriter output = new StringWriter();

HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();


I was getting errors like:

System.Web.HttpException: Error executing child request for handler System.Web.UI.Page'.

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.

System.Web.HttpException: Control 'ctl00_listItems' of type 'Repeater' must be placed inside a form tag with runat=server.


I stumbled on this article:




It suggested overriding a method (notice no call to the base method)


public class PageOverride : System.Web.UI.Page

{

   public override void VerifyRenderingInServerForm(System.Web.UI.Control control) {}

}


Worked perfectly!




Wednesday, May 9, 2012

Panel with a Visible property that won't update

What's wrong with this pseudo-code?

Panel p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");
//do some other random stuff
gridItems.DataBind();
//do more random stuff
p.Visible = true; //FAIL

The code will execute fine but even after setting the Visible property to true, a QuickWatch will show the property is still false.

The fix:

Panel p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");
//do some other random stuff
gridItems.DataBind();
//do more random stuff
//get fresh reference after DataBind
p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");

p.Visible = true; //WIN

Friday, February 17, 2012

using SqlDataSource in code

Sometimes there is a need to use a SqlDataSource object in the code...

ASPX:
<asp:SqlDataSource ID="sqlSelectUsers" runat="server"
ConnectionString="<%$ConnectionStrings:MainConnectionString %>"
ProviderName="<%$ ConnectionStrings:MainConnectionString.ProviderName %>"
SelectCommandType="StoredProcedure"
    SelectCommand="spSelectUsers">

<SelectParameters>
<asp:Parameter Name="RequestingUserID" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>


VB:
sqlSelectUsers.SelectParameters("RequestingUserID").DefaultValue = 2 //hard coded value for demo purposes
Dim dv As DataView = sqlSelectUsers.Select(DataSourceSelectArguments.Empty)
Dim dt As DataTable = dv.ToTable()

This will result in a DataTable for manual consumption.

Another way to parse CSV parameters for values not necessarily in a table

-- http://www.projectdmx.com/tsql/tblnumbers.aspx
CREATE TABLE dbo.Nbrs(n INT NOT NULL IDENTITY) ;
INSERT dbo.Nbrs DEFAULT VALUES ;
WHILE SCOPE_IDENTITY() < 500 INSERT dbo.Nbrs DEFAULT VALUES ;

-- http://www.projectdmx.com/tsql/sqlarrays.aspx

DECLARE @p VARCHAR(50)
SET @p = 'ALFKI,LILAS,PERIC,HUNGC,SAVEA,SPLIR,LONEP,GROSR'

SELECT SUBSTRING( ',' + @p + ',', n + 1, CHARINDEX( ',', ',' + @p + ',', n + 1 ) - n - 1 ) AS "value"
FROM Nbrs
WHERE SUBSTRING( ',' + @p + ',', n, 1 ) = ',' AND n < LEN( ',' + @p + ',' ) ;

drop table Nbrs    

Thursday, February 16, 2012

Convert a SQL CSV Parameter into a table

Consider the need to pass in a CSV parameter like this:

DECLARE @UserIDs_CSV VARCHAR(50)
SET @UserIDs_CSV = '1,2,4,5,8,9'

If that CSV parameter happens to correlate to a table, like in this case, Users... Use a query like this to convert the CSV parameter into a temp table...

SELECT UserID
into #SelectedUserIDs
FROM Users
WHERE CHARINDEX(
',' + cast(UserID as varchar(10)) + ',',
',' + @UserIDs_CSV + ','
) > 0

So now just use the temp table as you need for future queries...

select * from #SelectedUserIDs

Credit goes to http://www.projectdmx.com/tsql/sqlarrays.aspx

Monday, February 6, 2012

Getting a quicker SQL row count

Credit goes to Rick Caminiti at http://rickcaminiti.com/tips/alternative-efficient-tables-rowcount-sql/


SELECT COUNT(*) statements make a full table scans to return the total table’s row count, it can take a lot of time and a lot of “energy” for a large table.
There is another way to determine the total row count in a table by using the sysindexes system table. There is a column (ROWS) in it that contains the total row count for each table in your database.
You can use the syntax below to speed up the query by several times.  You can see this by setting statistics on, as shown below.


SET STATISTICS IO ON
GO
SELECT count(*) FROM tbTest
GO
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('tbTest') AND indid < 2
GO
SET STATISTICS IO OFF
GO



I tried my own test, and here are my results:


(1 row(s) affected)
Table 'myTable'. Scan count 1, logical reads 116, physical reads 1, read-ahead reads 176, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)
Table 'sysidxstats'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Wednesday, December 21, 2011

Reset Windows Media Player 12 To Default Settings

Here's a cool trick that allows you to reset WMP12 back to it’s default settings. This might be handy if you are encountering any issues of your own.
Simply to go Start > Run (or hold down the Windows Key and press R) and type in the following:
msdt.exe -id WindowsMediaPlayerConfigurationDiagnostic
Press enter and follow the prompts to reset WMP.

Thursday, December 8, 2011

SQL example for updating children records from a parent record

I just ran into this again, and I know I have had to do this several times before but it gets old having to look up such an activity that I may only do twice a year.

The scenario... There are four records:
ID=123, ParentID=null, Name="Bob"


ID=1000, ParentID=123, Name="Bob"
ID=1001, ParentID=123, Name="Bob"
ID=1002, ParentID=123, Name="Bob"

The requirement is to update Name="Joe" where ID=123, and then cascade the changes to the children records.  This could be done easily w/ the same proc that updates the parent, however in my situation that proc is being shared, so my solution is to make a new query that fetches the right info w/ a join and then updates:

UPDATE children
SET
Field1 = parent.Field1,
Field2 = parent.Field2,
Field3 = parent.Field3
from ExampleTable children
inner join ExampleTable parent on parent.ID = children.ParentID
WHERE children.ParentID = @ParentID

Monday, October 3, 2011

Clear the "must change password" checkbox for new SQL users.

It's very annoying to create a new SQL user and forget to clear the "User must change password at next login" checkbox.

This will result in an error message:
Login failed for user 'login_name'.  Reason: The password of the account must be changed.

If you try to clear the message, you get:
The CHECK_POLICY and CHECK_EXPIRATION options cannot be turned OFF when MUST_CHANGE is ON. (Microsoft SQL Server, Error: 15128)

One solution is to delete the user and create again, and clear the checkbox.  Another solution I found on Experts Exchange:
ALTER LOGIN UserLogin WITH PASSWORD = 'NewPassword' UNLOCK

Then you can uncheck 'Enforce password policy' and 'Enforce password expiration' or just run the following two sql commands:

ALTER LOGIN UserLogin WITH CHECK_EXPIRATION = OFF

ALTER LOGIN UserLogin WITH CHECK_POLICY = OFF


http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_23063893.html

Monday, September 12, 2011

Word 2007 document with comments is crashing

My coworker had a document that had around 30 comments and when she'd click on the comment to delete it, Word 2007 would crash.  She mentioned that the comment targets somehow were erased and the comments were orphaned but still in the document.

Word has a recovery mode that did not work.  I tried copy/pasting to a new document which did not work.  Even tried using a VBA macro to delete a comment, then altered it to select and delete these other comments.  That didn't work either.

I know Word 2007 uses the new .docx format, which is really just a zip file container.  So I unzipped the .docx file, dug around in the supporting XML files, and found two files.  There is a document.xml and a comments.xml and inside the comments.xml file is an ID in each node that the document.xml file references.  Pretty simple layout.

In the document.xml file, I searched for "w:comment" and found hits on nodes named
<w:commentRangeStart w:id="3" />
<w:commentRangeEnd w:id="3"/>
<w:commentReference w:id="3"/>

Those nodes match the comments.xml document that has
<w:comment w:id="3">

Furthermore, while searching through the document.xml file, the IDs for problematic comments just happened to have

<w:commentReference w:id="3"/>
but not

<w:commentRangeStart w:id="3" />
<w:commentRangeEnd w:id="3"/>

So... Remove the broken references in document.xml and now there are fully orphaned items in comments.xml so remove those nodes as well.  Save all docs, then rezip the folder and rename to .docx

The doc opens fine, and Word 2007 no longer crashes :)  Woohoo.

Thursday, September 1, 2011

Ensure deploys are not in debug mode



The <deployment retail=”true”/> Switch in Machine.config

If you are a server administrator and want to ensure that no one accidentally deploys an ASP.NET application in production with the <compilation debug=”true”/> switch enabled within the application’s web.config file, one trick you can use with ASP.NET V2.0 is to take advantage of the <deployment> section within your machine.config file.

Specifically, by setting this within your machine.config file:

<configuration>
    <system.web>
          <deployment retail=”true”/>
    </system.web>
</configuration>

You will disable the <compilation debug=”true”/> switch, disable the ability to output trace output in a page, and turn off the ability to show detailed error messages remotely.  Note that these last two items are security best practices you really want to follow (otherwise hackers can learn a lot more about the internals of your application than you should show them).

Setting this switch to true is probably a best practice that any company with formal production servers should follow to ensure that an application always runs with the best possible performance and no security information leakages.  There isn’t a ton of documentation on this switch – but you can learn a little more about it here.

Tuesday, August 30, 2011

WebResource.axd returns 404 and then starts working after a while on it's own


Original question that I posted:

http://stackoverflow.com/questions/6902650/webresource-axd-wont-update

http://forums.asp.net/t/1711550.aspx/1?WebResource+axd+returns+404+and+then+starts+working+after+a+while+on+it+s+own
We have a library of common controls, and I'm attempting to steer towards using embedded resources in it for images, JS, and CSS. It seems that upon each deploy to TEST/PROD, there is a window of time where WebResource.axd is returning a 404. After that window of time expires, suddenly the page starts serving out content properly. On my local DEV machine it seems that there are times when I can compile and reload a page that is using embedded resources, and it immediately shows a difference. Other times it responds like there is a cache waiting to expire.
Things I've tried:
- browsing from different machines to rule out local caching
- iisreset
- net stop w3svc
- delete temp files from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files and C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
- killing the inetinfo.exe process
- killing the w3wp.exe process
- disabling IIS Output Caching
- copying the URL and adding in an extra false querystring parameter to mimic a new page request
- pressing Ctrl-F5 :)
It seems rebooting fixes the issue.
My google kung-fu has diluted results filled with everyone's answer to check the namespace. I am confident the namespace is correct. After a while the resource will start serving out properly and the correct version. And if it DOES serve at some point, it seems logical to me that the namespace must be correct.
Any ideas? What other information can I provide?
Thanks,
James
Michigan, USA
OK, WOW... FINALLY stumbled a solution.  Ready? This is going to be a long one :)

While trying to get more information, I load Fiddler and I'm looking at the headers... when I come across
this standard .NET error (edited):
<html>
    <head>
        <title>The resource cannot be found.</title>
[snip]
    </head>
    <body bgcolor="white">
            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
            <h2> <i>The resource cannot be found.</i> </h2></span>
[snip]
            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
            </font>
    </body>
</html>
<!--
[HttpException]: This is an invalid webresource request.
   at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
<!--
This error page might contain sensitive information because ASP.NET is configured to show verbose error messages
using &lt;customErrors mode="Off"/&gt;. Consider using &lt;customErrors mode="On"/&gt; or &lt;customErrors
mode="RemoteOnly"/&gt; in production environments.-->
WHOA... there's a commented stack trace that is buried in the page?!?!  After a quick Google search and I come across a link to http://stackoverflow.com/questions/1096793/system-web-httpexception-this-is-an-invalid-script-resource-request and on that page I stumble across this comment by Rob Levine (http://stackoverflow.com/users/134754/rob-levine):
Believe it or not, if your dlls have embedded resources in them, and they are dated in the future this will happen (if you ever compile dlls in the UK and then immediately deploy them to US web servers you'll be well aware of this issue!). I can't remember the event log error this shows, but would know if I saw it - and it is not immediately obvious.
That is exactly the situation... I compile in Eastern Time, then deploy to Rackspace in Central Time.  After about an hour the resources begin to load again... it makes sense... the time stamps catch up!

Sunday, July 17, 2011

The page has one or more asp:Content controls that do not correspond with asp:ContentPlaceHolder controls in the Master Page.

I kept getting this error in the design view:
The page has one or more <asp:Content> controls that do not correspond with <asp:ContentPlaceHolder> controls in the Master Page.
A few Google searches, this is what I found to work for me:
Setting
<title></title>
instead of
<title />
solved the problem.
http://forums.asp.net/t/1302708.aspx