Blog

My blog serves as a way for me to post solutions to problems I solve at work or during the long hours of freelance work.


SQL Server Number of Rows in all Tables in a Database

by Ezekiel 7. November 2014 06:33

 

SELECT 

t.NAMEASTableName,

i.nameasindexName, 

p.[Rows], 

sum(a.total_pages)asTotalPages, 

sum(a.used_pages)asUsedPages, 

sum(a.data_pages)asDataPages,

(sum(a.total_pages)* 8)/ 1024 asTotalSpaceMB, 

(sum(a.used_pages)* 8)/ 1024 asUsedSpaceMB, 

(sum(a.data_pages)* 8)/ 1024 asDataSpaceMB

FROM 

sys.tablest 

INNERJOIN 

sys.indexesiONt.OBJECT_ID=i.object_id 

INNERJOIN 

sys.partitionspONi.object_id=p.OBJECT_IDANDi.index_id=p.index_id 

INNERJOIN 

sys.allocation_unitsaONp.partition_id=a.container_id 

WHERE 

t.NAMENOTLIKE'dt%'AND 

i.OBJECT_ID> 255 AND 

i.index_id<= 1 

GROUPBY 

t.NAME,i.object_id,i.index_id,i.name,p.[Rows] 

ORDERBY 

object_name(i.object_id)

Tags: ,

SQL | SQL Server

Show All Indexes in a SQL Server Table

by Ezekiel 3. October 2014 06:19

 

select*fromsys.indexes 

whereobject_id=(selectobject_idfromsys.objectswherename='PayrollSchedule')

Tags:

SQL

Media Screen Only for Standard Devices

by Ezekiel 3. October 2014 03:18

 

 /* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Tags:

CSS

How to Reset the Root Password in MySQL on Windows

by Ezekiel 3. September 2014 14:18

 

If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. However, this is insecure. For instructions on assigning passwords, see Section 2.12.2, “Securing the Initial MySQL Accounts”.

If you know the root password, but want to change it, see Section 13.7.1.6, “SET PASSWORD Syntax”.

If you set a root password previously, but have forgotten it, you can set a new password. The following sections provide instructions for Windows and Unix systems, as well as generic instructions that apply to any system.

 

Resetting the Root Password: Windows Systems

1. On Windows, use the following procedure to reset the password for all MySQL root accounts:

2. Log on to your system as Administrator.

3. Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.

If your server is not running as a service, you may need to use the Task Manager to force it to stop.

4. Create a text file containing the following statements. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

Write the UPDATE and FLUSH statements each on a single line. The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

5. Save the file. For this example, the file will be named C:\mysql-init.txt.

6. Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.

7. Start the MySQL server with the special --init-file option (notice that the backslash in the option value is doubled):

C:\> C:\mysql\bin\mysqld --init-file=C:\mysql-init.txt
If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.

The server executes the contents of the file named by the --init-file option at startup, changing each root account password.

You can also add the --console option to the command if you want server output to appear in the console window rather than in a log file.

If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option:

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe"
         --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.1\\my.ini"
         --init-file=C:\\mysql-init.txt

8. After the server has started successfully, delete C:\mysql-init.txt.

Tags:

MySQL

Keyboard Shortcuts in Remote Desktop Connection RDC

by Ezekiel 14. August 2014 08:28

 

CTRL+ALT+END: Open the Microsoft Windows NT Security dialog box (CTRL+ALT+DEL)

ALT+PAGE UP: Switch between programs from left to right (CTRL+PAGE UP)

ALT+PAGE DOWN: Switch between programs from right to left (CTRL+PAGE DOWN)

ALT+INSERT: Cycle through the programs in most recently used order (ALT+TAB)

ALT+HOME: Display the Start Meun (CTRL+ESC)

CTRL+ALT+BREAK: Switch the client computer between a window and a full screen

ALT+DELETE: Display the Windows menu

CTRL+ALT+Minus sign (-): Place a snapshot of the entire client window area on the Terminal server clipboard and provide the same functionality as pressing ALT+PRINT SCREEN on a local computer (ALT+PRT SC)

CTRL+ALT+Plus sign (+): Place a snapshot of the active window in the client on the Terminal server clipboard and provide the same functionality as pressing PRINT SCREEN on a local computer (PRT SC)

Tags: ,

rdc | remote desktop

String.Format

by Ezekiel 12. August 2014 03:56

 

Currency "{0:c}"

Date "{0:MM/dd/yyyy}"

Tags: ,

C# | General | Javascript | MVC | Razor Views

ASP.NET vNext

by Ezekiel 4. July 2014 12:50

 

http://www.hanselman.com/blog/IntroducingASPNETVNext.aspx

ASP.NET vNext will take things to the next level. Today, you run ASP.NET using the same CLR that desktop apps use. We’re adding a cloud-optimized (my cloud, your cloud, their cloud - server stuff) version optimized for server scenarios like low-memory and high-throughput.

ASP.NET vNext will let you deploy your own version of the .NET Framework on an app-by-app-basis. One app with new libraries can’t break an app next door with a different version. Different apps can even have their own cloud-optimized CLR of their own version. The CLR and cloud-optimized libraries are NuGet packages!

I can run ASP.NET vNext apps within Visual Studio, of course, and within IIS, but I can also easily "self-host" them from the command line or within my own application. This alpha includes command line tools for running and managing ASP.NET vNext apps.

One of the great aspects of environments like node or rails is that they are "no compile." Just change some code and hit refresh. With the next version of ASP.NET you get the power and throughput of the .NET runtime plus the "Roslyn" compiler-as-a-service for a "no-compile compile." That means means during development time you can just change your C# classes and hit Refresh in the browser. It's the power of .NET with the dynamism of a refresh-and-go development experience.

You’ll be able to put ASP.NET vNext on your existing servers, any hoster, and Azure of course.

You can opt in or out of the cloud optimized framework for compatibility. The next version of ASP.NET is modular and all about choice. your choice of framework, your choice of runtime, your choice of operating system, your choice of text editor.

ASP.NET VNEXT IS:

Cloud and server-optimized
ASP.NET MVC and Web API have been unified into a single programming model
No-compile developer experience
Dependency injection out of the box
Side by side - deploy the runtime and framework with your application
NuGet everything - even the runtime itself
All Open Source via the .NET Foundation and takes contributions
Oh, and by the way

ASP.NET vNext (and Rosyln) runs on Mono, on both Mac and Linux today. While Mono isn't a project from Microsoft, we'll collaborate with the Mono team, plus Mono will be added to our test matrix. It's our aspiration that it "just work."

Tags: ,

asp.net vnext

Delete an Index from a SQL Server Database

by Ezekiel 2. July 2014 11:12

 

DROPINDEXtable.index_name

Tags: , ,

SQL | SQL Server

Show All Indexes in a SQL Server Database

by Ezekiel 2. July 2014 11:05

 

SELECTDB_NAME()AS DatabaseName

, sc.name ASSchema_Name 

, o.name AS Table_Name 

, i.name AS Index_Name 

, i.type_desc AS Index_Type 

FROMsys.indexes

INNERJOINsys.objects o ON i.object_id= o.object_id 

INNERJOINsys.schemas sc ON o.schema_id= sc.schema_id 

WHERE i.name ISNOTNULL 

AND o.type='U' 

ORDERBY o.name, i.type

Tags: , ,

SQL | SQL Server

Entity Migrations Create Table

by Ezekiel 24. June 2014 07:26
 
public override void Up()
{
    CreateTable(
        "dbo.Carts",
        c => new
        {
            CartId = c.Int(nullable: false, identity: true),
            IP = c.String(),
            RecordId = c.Int(),
            ProductId = c.Int(),
            Count = c.Int(),
            CreatedDate = c.DateTime(),
        })
        .PrimaryKey(t => t.CartId);
 
}
 
public override void Down()
{
    DropTable("dbo.Carts");
}

Tags:

C# | Entity Migrations

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

by Ezekiel 22. April 2014 13:30
[No text]

Tags:

A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations

by Ezekiel 2. April 2014 14:06

Tags: ,

android | Android Development

A potentially dangerous Request.Form value was detected from the client

by Ezekiel 19. March 2014 09:23
[No text]

Tags:

MS Patterns & Practices

by Ezekiel 19. March 2014 07:16

http://pnp.azurewebsites.net/en-us/

Tags:

How to Turn off Chrome Notification

by Ezekiel 10. March 2014 13:10

 

Type the following in the browser address bar:

chrome://flags/

 

Search for the following using the browser find ( ctrl + f ):

Enable Rich Notifications Mac, Windows

 

Select disable in the dropdown.

 

Tags:

Chrome

Plug-in com.android.ide.eclipse.adt was unable to load class com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor

by Ezekiel 8. March 2014 00:17

 

Close the editor and reboot your computer.

Tags:

Android Development

ADT Bundle for Windows Download

by Ezekiel 26. February 2014 13:04

Tags:

android

SQL Alter Table Add Column with Default Value Update Table

by Ezekiel 6. February 2014 07:49

-- Adding New Column
ALTER TABLE TestTable
ADD SecondCol INT
GO


-- Updating it with Default
UPDATE TestTable
SET SecondCol = 0
GO


-- Alter
ALTER TABLE TestTable
ALTER COLUMN SecondCol INT NOT NULL
GO

Tags: , ,

SQL | SQL Server

CSS @Media Types

by Ezekiel 17. January 2014 04:20

‚Äč

All
Suitable for all devices.

Braille
Intended for braille tactile feedback devices.

Embossed
Intended for paged braille printers.

Handheld
Intended for handheld devices (typically small screen, limited bandwidth).

Print
Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media, and the media section of the Getting Started tutorial for information about formatting issues that are specific to paged media.

Projection
Intended for projected presentations, for example projectors. Please consult the section on paged media for information about formatting issues that are specific to paged media.

Screen
Intended primarily for color computer screens.

Speech
Intended for speech synthesizers. Note: CSS2 had a similar media type called 'aural' for this purpose. See the appendix on aural style sheets for details.

TTY
Intended for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities). Authors should not use pixel units with the "tty" media type.

TV
Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).

Tags:

CSS | Design

Copy a Website

by Ezekiel 9. January 2014 07:34

Tags:

A List of Responsive Web Design Template Websites

by Ezekiel 7. January 2014 13:26

Tags:

Responsive Design

Remove Text from Textbox during OnClick using Razor View

by Ezekiel 7. January 2014 10:49

 

            <div class="editor-field">
                @Html.TextAreaFor(model => model.Product.Description, new
                                {
                                    onfocus="(this.value == 'enter description') && (this.value = '')",
                                    onblur="(this.value == '') && (this.value = 'enter description')"
                                })
                @Html.ValidationMessageFor(model => model.Product.Description)
            </div> 

 

Tags: , ,

Javascript | MVC | Razor Views

RESTful Web Service Test Clients

by Ezekiel 25. December 2013 16:20

Tags:

ASP.NET C# MVC Unit Testing

by Ezekiel 21. December 2013 03:48

 

[Fact]
public void ListActionReturnsListOfCategories()
{
    // Arrange

    // create the mock
    var mockRepository = new Mock<ICategoryRepository>();

    // create a list of categories to return
    var categories = new[] { new Category {Id = 1, Name = "test"} };

    // tell the mock that when FindAll is called,
    // return the list of categories
    mockRepository.Setup(cr => cr.FindAll()).Returns(categories);

    // pass the mocked instance, not the mock itself, to the category
    // controller using the Object property
    var controller = new CategoryController(mockRepository.Object);

    // Act
    var result = (ViewResult) controller.List();

    // Assert
    var listCategories = Assert.IsAssignableFrom<IEnumerable<Category>>(result.ViewData.Model);
    Assert.Equal(1, listCategories.Count());           
}

 

[Fact]
public void ListActionReturnsListOfCategories()
{
    // Arrange
    var mockService = new Mock<ICategoryService>();
    var categories = new[] { new Category { Id = 1, Name = "test" } };
    mockService.Setup(cr => cr.FindAll()).Returns(categories);
    var controller = new CategoryController(mockService.Object);

    // Act
    var result = (ViewResult) controller.List();

    // Assert
    var listCategories = Assert.IsAssignableFrom<IEnumerable<Category>>(result.ViewData.Model);           
    Assert.Equal(1, listCategories.Count());
}

 [Fact]
public void PriceIsFormattedAsCurrency()
{
    // Arrange
    var product = new Product {Price = 9.22m};
    var presentationProduct = new
        PresentationProductStub(product);

    // Act
    string cost = presentationProduct.DisplayPrice;

    // Assert
    Assert.Equal("$9.22", cost);
}

[Fact]
public void DefaultUrlRoutesToCategoryControllerAndListAction()
{
    // Arrange
    var context = ContextHelper.GetMockHttpContext("~/");
    var routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);

    // Act
    RouteData routeData = routes.GetRouteData(context.Object);

    // Assert
    RouteTestingHelper.AssertRouteData(routeData, "Category", "List", "");
}

[Fact]
public void ProductEditUrlRoutesToProductControllerAndListAction()
{
    // Arrange
    var context = ContextHelper.GetMockHttpContext("~/Product/Edit/12");
    var routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);

    // Act
    RouteData routeData = routes.GetRouteData(context.Object);

    // Assert
    RouteTestingHelper.AssertRouteData(routeData, "Product", "Edit", "12");
}

[Fact]
public void ListActionReturnsViewResultWithDefaultName()
{
    // Arrange
    var mockService = new Mock<ICategoryService>();
    var controller = new CategoryController(mockService.Object);

    // Act
    var result = controller.List();

    // Assert
    var viewResult = Assert.IsType<ViewResult>(result);           
    Assert.Empty(viewResult.ViewName);
}

   /// <summary>
    ///This is a test class for LibraryCoreTest and is intended
    ///to contain all LibraryCoreTest Unit Tests
    ///</summary>
    [TestClass()]
    public class LibraryCoreTest
    {

        private LibraryCore _target;
        private Mock<IMemberManager> _mock;

        /// <summary>
        ///A test for CalculateMemberShipCost
        ///</summary>
        [TestMethod()]
        public void CalculateMemberShipCostTest()
        {
            _mock = new Mock<IMemberManager>();
            _target = new LibraryCore(_mock.Object);
            Member member = new Member()
            {
                MemberID=1,
                FirstName="Erandika",
                SecondName="Sandaruwan",
                Age=25,
                MaximumBookCanBorrow=4,
            };

            _mock.Setup(x => x.GetMember(It.IsAny<int>())).Returns(member);
   
            int memberID = 1;
            double expected = 12;
            double actual;
            actual = _target.CalculateMemberShipCost(memberID);
            Assert.AreEqual(expected, actual); 
        }
    }

 [TestMethod] // [Fact] for XUnit framework
public async Task YourTestName()

{

     // Arrange

     // mock/stub your async method, use a framework or do it yourself - Task.FromResult() is the key

     // SomeMethodAsync() returns Task<string>

     var fakeRepository = new Mock<ISomeRepository>();

     fakeRepository.Setup(m => m.SomeMethodAsync()).Returns(Task.FromResult("your object to return"));

     // constructor injection, or other technique (e.g. property injection)

     var target = new SomeController(fakeRepository.Object);

     // Act

     // SomeMethodAsync() uses mocked/stubed ISomeRepository inside

     ActionResult result = await target.SomeMethodAsync();

     // Assert

     // your assertion

}

 

Tags: , ,

MVC | Unit Testing

How to Use PageList.MVC

by Ezekiel 6. December 2013 15:53

 

Run the following in Package Manager Console.

PM> Install-Package PagedList.Mvc

 

Controller -

        public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var products = from s in db.Products
                           select s;

            switch (sortOrder)
            {
                case "name_desc":
                    products = products.OrderByDescending(s => s.Name);
                    break;
                case "Date":
                    products = products.OrderBy(s => s.Price);
                    break;
                case "date_desc":
                    products = products.OrderByDescending(s => s.Price);
                    break;
                default:  // Name ascending
                    products = products.OrderBy(s => s.Name);
                    break;
            }

            int pageSize = 300;
            int pageNumber = (page ?? 1);

            return View(products.ToPagedList(pageNumber, pageSize));
        }

 

 

Front-end -

 

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
 

Tags: ,

MVC

The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

by Ezekiel 6. December 2013 13:30

 

I received this error when trying to use PageList.MVC without adding sorting to the controller.

Tags: ,

MVC

Entity Framework Code First Migrations

by Ezekiel 3. November 2013 06:44

 

Tools -> Libray Package Manager -> Package Manager Console

 

Enter the following if migrations have not been enabled on the project -

Enable-Migrations


Add-Migration AnyNameYouWantClass

Update-Database

 

Should add the database changes.

Tags: ,

Code First | Entity Framework

Entity Framework Code First Migrations

by Ezekiel 3. November 2013 06:44

 

Tools -> Libray Package Manager -> Package Manager Console

 

Enable-Migrations
Add-Migration AddMyClass
Update-Database

Tags:

Using 'xpstar.dll' version '2009.100.1600' to execute extended stored procedure 'xp_instance_regread'. This is an informational message only; no user action is required.

by Ezekiel 1. November 2013 06:56

 

Found this in my logs. interesting.

Tags: ,

SQL Server

Allow NuGet to Download Missing Package During Build

by Ezekiel 4. March 2013 06:37

 

Error -

Package restore is disabled by default. To give consent, open the Visual Studio Options dialog, click on Package Manager node and check 'Allow NuGet to download missing packages during build.' You can also give consent by setting the environment variable 'EnableNuGetPackageRestore' to 'true'. HelloWebAPI

 

Solution -

tools > options > package manager 

Tags: ,

NuGet | Visual Studio

Entity Framework Power Tools Beta 3

by Ezekiel 28. February 2013 15:29

 

This is sweet, If the database already exists this tool will create the Code First classes for you.

http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d

Tags: ,

C# | Code First

Microsoft SharePoint Workflow Template Not Showing in Visio 2010

by Ezekiel 22. January 2013 04:46

 

1. Look under "Flowchart". If SharePoint Workflow template isn't found you have to get a valid product key for "Visio Premium 2010".

2. Go to Control Panel > Programs.

3. Select Microsoft Visio 2010.

4. Click the change button at the top.

5. Select Product key.

6. Enter valid "Visio Premium 2010" product key.

After successfully doing the step above you should see the template under "Flowchart" group.

 

 

Tags: , ,

Office | SharePoint 2010 | Visio

JQuery Replace Globally

by Ezekiel 25. November 2012 04:55

 

Use /something/g.

var str = "This is sample text for a sample replace";
str = str.replace(/ /g, "-");

Tags: ,

Javascript | JQuery

MVC Data Annotation

by Ezekiel 12. November 2012 17:36

 

[Key]

[Required]

[ComplexType]

[ScaffoldColumn(false)]

[DisplayName("Category")]


[MaxLength(10), MinLength(5)]

[MaxLength(10, ErrorMessage="BloggerName must be 10 characters or less"), MinLength(5)]

[ConcurrencyCheck, MaxLength(10, ErrorMessage="BloggerName must be 10 characters or less"), MinLength(5)]

[Display(Name = "Name", Description = "Enter the name of the product.")]

[HttpPost]

[Timestamp]

[Table("InternalBlogs")]

[Column(“BlogDescription", TypeName="ntext")]

[DatabaseGenerated(DatabaseGenerationOption.Computed)]

[ForeignKey("BlogId")]

[InverseProperty("CreatedBy")]

Tags: , ,

C# | MVC

How to Install Visual Studio Tools for Applications VSTA

by Ezekiel 10. October 2012 05:37

 

1. Find your Microsoft Office 2010 installl under Programs and Features

2. Highlight and click "Change" button.

3. Select "Add or Remove features".

4. Drill down from "Microsoft InfoPath" to "Visual Studio Tools for Applications"

5. Select "Enable".

 

Tags: ,

C# | InfoPath | Visual Studio

NuGet TinyMCE Install

by Ezekiel 16. September 2012 07:45

 

Launch Package Manager Console:

Tools > Library Package Manager > Package Manager Console

 

Copy and paste this line below and hit enter:

 PM> Install-Package TinyMCE

Tags: , , ,

MVC | NuGet | TinyMCE

How to do Top 1 in Oracle

by Ezekiel 15. August 2012 04:03

 

select fname from MyTbl where rownum = 1

Tags: , ,

SQL | Oracle

Create Metro Style Icons with Metro Studio

by Ezekiel 22. June 2012 04:41

 

This is a cool little app for create beautiful metro style icons. 

After registering the site will email the product key.

http://www.syncfusion.com/downloads/metrostudio/confirmation/155873  

 

 

Tags: , ,

icons | Metro

MVC HTTP Post Edit View Model Data Using FormCollection in C#

by Ezekiel 16. June 2012 18:16

 

Model View Class -

    public class ProductViewModel
    {
        public Product Product { get; set; }
        public List<Image> Images { get; set; }
    }

 

Controller Method -

        //
        // POST: /Manager/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection, IEnumerable<HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                Product product = db.Products.Single(p => p.ProductId == id);

                UpdateModel(product, "Product");

                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();

                // Insert images
                InsertUploadFiles(product, files);

                return RedirectToAction("Index");
            }

            return Redirect("index");
        } 

 

 UI -

@using (Html.BeginForm("edit", "manager", FormMethod.Post, new { id = Model.Product.ProductId, enctype = "multipart/form-data" }))

 

Tags: , ,

ASP.NET | C# | MVC

How to Install Code First EntityFramework NuGet

by Ezekiel 13. June 2012 15:44

 

In Visual Studio go to -

Tools > Library Package Manager > Package Manager Console

 

At the command prompt copy and paste the code from this site -

http://nuget.org/packages/entityframework

 

Tags: , ,

MVC | Code First

Maximum request length exceeded.

by Ezekiel 10. June 2012 16:27

 

I was getting this error message when uploading more then two image files.

 

Add this to your web.confg -

<httpRuntime requestValidationMode="2.0" maxRequestLength="20192" />

 

 

Tags: , ,

.NET 4.0 | ASP.NET | MVC

Unable to update the EntitySet 'Categories' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

by Ezekiel 6. June 2012 14:34

 

I had to add a primary key to the database table I was trying to insert data into.

Tags: ,

LINQ to EntityFrame | SQL Server

SharePoint 2010 Development Using Visual Studio 2010 Videos

by Ezekiel 5. June 2012 04:04

Tags: ,

SharePoint 2010

SharePoint Designer 2007 Download

by Ezekiel 5. June 2012 04:01

Tags:

SharePoint 2007

Metro Style Icons

by Ezekiel 1. June 2012 04:03

Tags: , ,

Metro

SQL Combine Multiple Records into One Record.

by Ezekiel 7. May 2012 04:06

 

DECLARE @List VARCHAR(MAX)

SELECT @List = COALESCE(@List + ' | ' , '') + s.Name
FROM table1 t
JOIN table2 t2 ON t2.Id = t.Id
WHERE t.Id = 1

SELECT @List

Tags: , ,

SQL | SQL Server

How to Add Web Reference in Visual Studio 2010

by Ezekiel 23. April 2012 07:02

 

1. Right click on project.

2. Selelct "Add Service Reference".

3. Click the "Advanced.." button at the bottom. 

4. On the next screen click "Add Web Reference" button at the bottom.

 

 

Tags: , ,

Visual Studio

C# LINQ Examples

by Ezekiel 6. April 2012 04:42

Tags: ,

C# | LINQ

File Upload Error Cannot Access a Closed File .NET 2.0

by Ezekiel 4. April 2012 05:07

 

To fix this I changed the httpRuntime node in the web.config

Changed From - 

<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="8192" />

 

Changed To -

<httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>

 

Works perfectly now!!!

Tags: , ,

ASP.NET | C#

Paint.NET, GIMP Free Photo Editing Software

by Ezekiel 20. March 2012 03:34

Tags:

Photo Editing Software

C# Load DropDownList Data Using LINQ and Entity Framework

by Ezekiel 19. March 2012 02:50

 

        private void LoadDropDownList()
        {
            // Clear all items in drop down
            ddl.Items.Clear();

            using (Entities entities = new Entities())
            {
                var ddlValues = from s in entities.DBTableName
                                 select s;

                if (ddlValues != null)
                {
                    ddl.DataTextField = "TextFieldValue";
                    ddl.DataValueField = "Id";
                    ddl.DataSource = ddlValues.ToList();
                    ddl.DataBind();
                }
            }           
        }

Tags: , , ,

C# | LINQ to EntityFrame

Email Text Messages for AT&T, Verizon, T-Mobile, Sprint, Virgin, US Cellular, Nextel, Boost, Alltel

by Ezekiel 9. March 2012 03:12

Tags:

Mobile Phone

DotNetNuke Object Reference not Set to an Instance of an Object

by Ezekiel 16. February 2012 03:30

 

We had to moved an application which was developed about 10 years ago in .NET 1.1 and DotNetNuke. I'm not sure what version of DotNetNuke. We had to upgrade the .NET Framework to use 2.0. The app ran fine on the old servers, but on the new servers the app was erroring every time the user hit the database. I spent about 3 days trying to figure out what is wrong with this dumb thing. Well, turns out it was a very simple fix.

 

I added the following to the web.config and BOOM it works!

 <system.web>
  <pages validateRequest="false" enableEventValidation="false" enableViewStateMac="true" />
 </system.web>

adding enableEventValidation="false" to the pages node did the trick.

 

 

 

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

  <%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
   <system.web>
       <compilation debug="true"/>
   </system.web>
</configuration>

 

 

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario. 

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
   System.Web.Util.StringUtil.GetStringHashCode(String s) +32
   System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() +288
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +59
   System.Web.UI.WebControls.RadioButtonList.LoadPostData(String postDataKey, NameValueCollection postCollection) +293
   System.Web.UI.WebControls.RadioButtonList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +13
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +373
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2054

[PageLoadException: Object reference not set to an instance of an object.]
   DotNetNuke.Exceptions.ProcessPageLoadException(Exception exc, String URL) in C:\Projects\DOTNetNuke\components\Exceptions\Exceptions.vb:181
   DotNetNuke.BasePage.Page_Error(Object Source, EventArgs e) in C:\Projects\DOTNetNuke\components\BasePage.vb:41
   System.Web.UI.TemplateControl.OnError(EventArgs e) +107
   System.Web.UI.Page.HandleError(Exception e) +84
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6219
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +369
   System.Web.UI.Page.ProcessRequest() +200
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +23
   System.Web.UI.Page.ProcessRequest(HttpContext context) +201
   ASP.default_aspx.ProcessRequest(HttpContext context) +5
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +406
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76

 

 

 

 

Tags: , ,

ASP.NET | C# | DotNetNuke

SQL Server Search all Tables for Value

by Ezekiel 9. February 2012 06:29


DECLARE @SearchStr nvarchar(100)
SET @SearchStr = 'SearchTerm'

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL
   
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
           
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )
   
            IF @ColumnName IS NOT NULL
           
            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END   
    END

    SELECT ColumnName, ColumnValue FROM #Results

DROP TABLE #Results

Tags: ,

SQL | SQL Server

C# SharePoint 2010 Location of Microsoft.SharePoint SharePoint.dll

by Ezekiel 2. February 2012 04:00

 

Location of SharePoint.dll -

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

 

I was trying to add a reference to the SharePoint 2010 dll in one of my project.s

Tags: , , ,

C# | SharePoint 2010 | Visual Studio

Location of SharePoint 2010 Error Logs

by Ezekiel 25. January 2012 04:05

 

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS

Tags:

SharePoint 2010

C# How to Test a Website is Working or not With HttpWebRequest HttpWebResponse

by Ezekiel 24. January 2012 03:38

 

public static bool WebSiteIsAvailable(string Url)
{
  string Message = string.Empty;
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
 
  // Set the credentials to the current user account
  request.Credentials = System.Net.CredentialCache.DefaultCredentials;
  request.Method = "GET";
 
  try
  {
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
      // Do nothing; we're only testing to see if we can get the response
    }
  }
  catch (WebException ex)
  {
    Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
  }
 
  return (Message.Length == 0);
}

Tags: , ,

C#

SQL Server Saving Changes is not permitted.

by Ezekiel 21. January 2012 07:59

 

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes th require the table to be re-created.

 

Go to: tools -> options -> designers

  

Uncheck "Prevent saving changes that require table re-creation.

Click the okay button.

Should be good to go!

 

Tags:

SQL Server

Using Team Foundation Server 2010 Source Control with Visual Studio 2008

by Ezekiel 19. January 2012 11:08

 

To be able to connect to TFS from VS 2008, you need to install the Team Explorer.

To be able to connect from VS 2008 to TFS 2010, you need to install VS 2008 SP 1 and then the Forward Compatibility Update.

To connect VS 2003 to TFS, you need the MSSCCI provider.

 

I also opened RegEdit and added the URL to the TFS collection.

 

Navigate in RegEdit to -

hkey_current_user\software\microsoft\visualstudio\9.0\teamfoundation\servers

 

Create a new string key.

Name it the name of the server you are trying to connect to.

Double click the new key and enter the URL.

 

Enter URL to TFS collection -

http//servername:8080/tfs

 

 

Tags: , , ,

Team Server Foundation | Visual Studio

C# How to Cache Data Using Generic Method

by Ezekiel 9. December 2011 03:31

 

using System;
using System.Web;
using System.Web.Caching;
using System.Collections.Generic;
using System.Linq;
using RoboticsDataCapture.Model;

namespace MyNameSpace
{
    /// <summary>
    /// Cache wrapper to handle caching data
    /// </summary>
    public static class CacheWrapper
    {
        /// <summary>
        /// Generic cache method
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="expiration">When cache expires</param>
        /// <param name="fetcher">Generic method to search cache</param>
        /// <returns></returns>
        public static T CacheFetch<T>(string key, DateTime expiration, Func<T> fetcher) where T : class
        {
            Cache DataCache = HttpContext.Current.Cache;

            // Cache if the key is not null or blank
            if ((key ?? "").Length <= 0)
            {
                return fetcher();
            }

            T result = DataCache[key] as T;

            if (result == null)
            {
                result = fetcher();

                if (result == null)
                {
                    DataCache.Remove(key);
                }
                else
                {
                    DataCache.Add(key, result, null, expiration,
                        Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
                }
            }

            return result;
        }
    }

    /// <summary>
    /// Class using generic caching of entityframe database calls
    /// </summary>
    public class MyClass
    {
        public int Id { get; set; }
        public string Name { get; set; }

        // Set cache expiration
        private static DateTime expiration = DateTime.Now.AddHours(24);

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static List<MyClass> GenericList()
        {
            return CacheWrapper.CacheFetch<List<MyClass>>("CachedDataName", expiration, () =>
            {
                using (Entities entities = new Entities())
                {
                    var databaseReturn = from t in entities.Table
                                         select new MyClass
                                          {
                                              Id = t.Id,
                                              Name = t.Name
                                          };

                    return databaseReturn.ToList();
                }
            });
        }
    }
}

Tags: , , , ,

ASP.NET | C# | Generics | Cache | LINQ to EntityFrame

C# Calling a Method Asynchronously using a Delegate

by Ezekiel 6. December 2011 07:16

 

 using System;

namespace NameSpaceName
{
    public class ClassName
    {
        private delegate void MyDelegate();
        private static MyDelegate caller;

        public static void Method()
        {
            // Log user action in audit log
            caller = new MyDelegate(MethodToCallFromDelegate);
            IAsyncResult result = caller.BeginInvoke(null, null);
        }

        private static void MethodToCallFromDelegate()
        {
           
        }
    }
}

Tags: , , ,

.NET 4.0 | C#

C# ASP.NET How Make All Controls Readonly on Web Form

by Ezekiel 21. November 2011 05:00

 

         private void MakeReadOnly(Control c)
        {
            foreach (Control childControl in c.Controls)
            {
                if (childControl.GetType() == typeof(TextBox))
                {
                    ((TextBox)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(CheckBox))
                {
                    ((CheckBox)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(DropDownList))
                {
                    ((DropDownList)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(Button))
                {
                    ((Button)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(RadioButtonList))
                {
                    ((RadioButtonList)childControl).Enabled = false;
                }
                else if (childControl.GetType() == typeof(ImageButton))
                {
                    ((ImageButton)childControl).Enabled = false;
                }
                if (childControl.Controls.Count > 0)
                {
                    MakeReadOnly(childControl);
                }
            }
        }

 

How to call -

MakeReadOnly((Control)this); 

Tags: , ,

ASP.NET | C#

ASP.NET 4.0 Web.config Transform

by Ezekiel 16. November 2011 02:18

 

If you are converting an old app which uses the old style of web.config. For example, having multiple config files named dev, qa, live etc. and you want to use the new transform build features.

You have go to the properties of the web.config, Build Action: Content. Otherwise, publishing will publish all the .config files. 

 

Tags: ,

.NET 4.0 | ASP.NET

Could not load file or assembly CrystalDecisions.Web Version=10.5.3700.0 or one of its dependencies. The system cannot find the file specified.

by Ezekiel 8. November 2011 07:20

 

Visual Studio 2008 has to be install. Then run this on your server.

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\CrystalReports10_5\CRRedist2008_x86.msi

 

Tags: ,

Crystal Reports

C# How to Truncate at Word by Certain Length

by Ezekiel 28. October 2011 09:34

 

        public static string TruncateAtWord(string value, int length) {
            if (value == null ||
                value.Length < length ||
                value.IndexOf(" ", length) == -1)
            {
                return value;
            }

            return value.Substring(0, value.IndexOf(" ", length)) + "...";
        }

Tags: ,

C#

ASP.NET Routing to Default Page

by Ezekiel 25. October 2011 04:53

 

I was stunk on this problem for a while. I tried adding a route to the default page in route table in the global.asax. That didn't work. The solution is so simply

 

<asp:HyperLink ID="HomeLink" NavigateUrl="~/" runat="server">« Back to Home</asp:HyperLink> 

Tags: , , ,

ASP.NET

ASP.NET UpdatePanel Leaving Extra Spaces When Hidden

by Ezekiel 25. October 2011 03:14

 

I had a dropdownlist which when an certain option is selected it would trigger the updatepanel to show it's contents. The problem is when the user selected another option the panel is hidden, but it would leave extra spaces.


Solution:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" RenderMode="Inline">


Add RenderMode="Inline" should do the trick!

Tags: , , ,

ASP.NET | UpdatePanel

C# Generic Extension Method to Move an Item to the Top of a Generic List

by Ezekiel 19. October 2011 07:54

 

    public static class ListExtensions
    {
        public static List<T> MoveToFront<T>(this List<T> list, Predicate<T> match)
        {
            int idx = list.FindIndex(match);

            if (idx != -1)
            {
                if (idx != 0) // move only if not already in front
                {
                    T value = list[idx]; // save matching value
                    list.RemoveAt(idx); // remove it from original location
                    list.Insert(0, value); // insert in front
                }

                return list;
            }

            return list; // matching value not found
        }
    }

 

How to use -

ClassName.ListMethod().MoveToFront(i => i.Id == 0); 

Tags: , , ,

C# | LAMBDA | Generics

Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.

by Ezekiel 23. September 2011 05:27

 

1. Open IIS

2. Select the app pool the application uses.

3. Click Advanced Settings 4. Change Enable 32-bit Application.

5. Save changed and recycle app pool.

Tags: ,

.NET 4.0 | IIS

MSDTC on server 'servername' is unavailable

by Ezekiel 3. August 2011 04:12

 

Resolution -

On the server where the trigger resides, you need to turn the MSDTC service on.

You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES.

Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.

Tags:

Command line arguments will not be passed

by Ezekiel 14. July 2011 14:34

 

Ran into this problem when I tried to publish and then the next time I debugged the app. Got this error.

This will fix it: GOTO the Project security tab and do this

1. Click 'This is a partial trust application'

2. Click Advanced Button (toward the bottom)

3. unClick 'Debug this application with the selected permission set'

4. Click 'OK'

5. Click 'This is a full trust application' (this will undo step #1)

Tags:

Block IPs from Website

by Ezekiel 19. June 2011 16:43

 

Master Page_Load function -

 

        protected void Page_Load(object sender, EventArgs e)
        {
            // Check for blocked IPs
            string userIP = HttpContext.Current.Request.UserHostAddress;
            string blockedIPs = ConfigurationManager.AppSettings["blockedIPs"];
            string[] ips = null;

            if (blockedIPs != null)
            {
                ips = blockedIPs.Split(',');
            }

            foreach (string ip in ips)
            {
                if (userIP == ip)
                {
                    HttpContext.Current.Response.StatusCode = 403;
                    HttpContext.Current.Response.End();
                    break;
                }
            }
        }

 

Web.config -

 

  <appSettings>
    <add key="blockedIPs" value="127.0.0.1" />
  </appSettings>

Tags: , ,

ASP.NET | C#

Insert into Table Using a SQL Select Statement

by Ezekiel 5. June 2011 05:22

 

INSERT INTO table1 (column1, column2)
SELECT column3, column4 FROM table2

Tags: , ,

SQL | SQL Server

Getting WCF Project Running on IIS 7.0

by Ezekiel 28. April 2011 06:14

 

Open a command prompt as Adminstrator

Navigate to the folder:
cd C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

Execute command:
ServiceModelReg.exe -i

Tags: , ,

C# | WCF | IIS

C# Unit Testing with NUnit

by Ezekiel 7. April 2011 09:45


using System;
using NUnit.Framework;

namespace UnitTestApplication.UnitTests
{
       [TestFixture()]
       publicclass Calculator_UnitTest
       {
              private UnitTestApplication.Calculator calculator = new Calculator();

              [SetUp()]
              publicvoid Init()
              {
                     // some code here, that need to be run
                     // at the start of every test case.
              }


              [TearDown()]
              publicvoid Clean()
              {
                     // code that will be called after each Test case
              }


              [Test]
              publicvoid Test()
              {

              }   
    }
}


NUnit framework support following assertions:

Assert()
AssertEquals()
AssertNotNull()
AssertNotNull()
AssertNull()
AssertSame()
Fail()


What Should Be Tested?

This is a common and valid question. Typical test cases are:

   1. Test for boundary conditions, e.g. our Calculator class only multiply signed integers, we can write a test for multiplying two big numbers and make sure our application code handles it.
   2. Test for both success and failure.
   3. Test for general functionality.

Tags: , ,

NUnit

Add Tooltip To Checkbox List Using C#

by Ezekiel 21. February 2011 04:02

 

        <asp:CheckBoxList ID="CheckboxList" runat="server">
           <asp:ListItem Text="Option1&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option1"></asp:ListItem>
           <asp:ListItem Text="Option2&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option2"></asp:ListItem>
           <asp:ListItem Text="Option3&nbsp;<img src='App_Themes/Main/Images/information.png' alt='' />" Value="option3"></asp:ListItem>
        </asp:CheckBoxList>

 

        protected void Page_Load(object sender, EventArgs e)
        {
            // Set tool tips
            SetCheckBoxListToolTips();
        }


        /// <summary>
        /// Sets meds checkboxlist tool tips
        /// </summary>
        private void SetCheckBoxListToolTips()
        {
            Medications.Items[0].Attributes.Add("title", "Tooltip message here");
            Medications.Items[1].Attributes.Add("title", "Tooltip message here");
            Medications.Items[2].Attributes.Add("title", "Tooltip message here");
 }

Tags: , ,

ASP.NET | C#

How to use iTextSharp to Merge HTML to PDF

by Ezekiel 9. February 2011 08:27

 

            // IText html to pdf
            Document document = new Document(PageSize.LETTER, 10, 10, 10, 10);

            using (MemoryStream output = new MemoryStream())
            {
                PdfWriter wri = PdfWriter.GetInstance(document, output);

                document.Open();
                document.NewPage();

                StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

                List<iTextSharp.text.IElement> objects = HTMLWorker.ParseToList(new StreamReader(tempHtmlFile, Encoding.Default), styles);

                for (int k = 0; k < objects.Count; k++)
                {
                    document.Add((IElement)objects[k]);
                }

                document.Close();

                return output.ToArray();
            }

Tags: ,

C#

LINQ to DataTable Function

by Ezekiel 9. February 2011 05:45

 

        private static DataTable LinqToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();

            // column names
            PropertyInfo[] oProps = null;

            if (varlist == null) return dtReturn;

            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others will follow
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;

                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                        == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }

                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }

                DataRow dr = dtReturn.NewRow();

                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                    (rec, null);
                }

                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        }

 

        How to use -

        public static DataSet GetClinicReportData(int clinicId)
        {
            using (Entities entities = new Entities())
            {
                var clinic = from c in entities.ClinicReportData(clinicId)
                                       select c;

                DataTable dt = LinqToDataTable(clinic);
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);

                return ds;
            }
        }

Tags: ,

C# | LINQ to DataTable

How To Delete Old Team Foundation Server Work Spaces

by Ezekiel 8. February 2011 07:13

 

To delete old workspace in tfs -

1. Open vs2010 command prompt
2. tf workspace /delete (workspace name)
3. Yes


If you need to undo pending changes -

1. tf undo /workspace:(workspace name) /recursive $/*
2. Re-run delete command line

 

Tags: , ,

Team Server Foundation

Sorting Functionality in GridView

by Ezekiel 3. January 2011 10:25

 

        protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            Users.BindGridViewData(this, sort);
        }


        private string GetSortDirection(string column)
        {
            string sortDirection = "DESC";
            string sortExpression = ViewState["SortExpression"] as string;
           
            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                   
                    if ((lastDirection != null) && (lastDirection == "DESC"))
                    {
                        sortDirection = "ASC";
                    }
                }
            }
           
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

Tags: , ,

ASP.NET | C# | GridView

Change Control Background Color When Validator Fails

by Ezekiel 30. December 2010 05:43

 

Javascript -

function fnOnUpdateValidators()
{
   for (var i = 0; i < Page_Validators.length; i++)
   {
      var val = Page_Validators[i];
      var ctrl = document.getElementById(val.controltovalidate);
      if (ctrl != null && ctrl.style != null)
      {
         if (!val.isvalid)
            ctrl.style.background = '#FFAAAA';
         else
            ctrl.style.backgroundColor = '';
      }
   }
}

 

Put this in C# Page_Load method  -

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");

 

Tags: , , ,

ASP.NET | C# | Javascript

ASP.NET Email Regular Expression Validator

by Ezekiel 10. December 2010 07:54

 

                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1"                            
                            ControlToValidate="ControlName"
                            Text="*"
                            Display="Dynamic" CssClass="redTextBlod" SetFocusOnError="true"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            runat="server"></asp:RegularExpressionValidator>

Tags: ,

ASP.NET

ASP.NET 4.0 SEO URL Routing

by Ezekiel 8. December 2010 06:44

 

Add this to your Global.asax.cs file -

 

        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        void RegisterRoutes(RouteCollection routes)

        {
            // Ignore request for resource files
            routes.Ignore("{resource}.axd/{*pathInfo}");

            // Register a route for forms/{formName}
            routes.MapPageRoute(
               "SignOnRequest",
               "forms/{formName}",
               "~/SignOnRequest.aspx"
            );
        }

 

 

There's many different ways to reference this route in your code -

 

Page.GetRouteUrl("SignOnRequest", new { formName = "signonrequest" });

http://www.yourdomain.com/forms/signonrequest

 

Tags: , , ,

.NET 4.0 | ASP.NET | C#

Submit Your Sitemap to Yahoo, Bing, and Ask Search Engines

by Ezekiel 30. November 2010 05:02

 

Use these URLs below.  Replace "www.yoursite.com" with your website's domain name.

 

http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=SitemapWriter&url=www.yoursite.com/sitemap.xml?redirect=false

http://www.bing.com/webmaster/ping.aspx?siteMap=www.yoursite.com/sitemap.xml

http://submissions.ask.com/ping?sitemap=www.yoursite.com/sitemap.xml

Tags:

Webmasters

Radio Buttons not Showing in IE

by Ezekiel 24. November 2010 06:51

 

I was using this CSS class and my radio buttons wouldn't show in IE only.  Worked fine in Firefox.

table.data input
{
    margin: 0;
    color: #781351;
    background: #fffff;
    border-left: 1px solid #bdd3a5;
    border-right: 1px solid #bdd3a5;
    border-top: 0 none;
    border-bottom: 0 none;
    height: 100%;
}

 

You need to give height a value other then a percent.  Modified version.

table.data input
{
    margin: 0;
    color: #781351;
    background: #fffff;
    border-left: 1px solid #bdd3a5;
    border-right: 1px solid #bdd3a5;
    border-top: 0 none;
    border-bottom: 0 none;
    height: 20px;
}

Tags: , ,

ASP.NET | CSS

ValidateRequest="false" Doesn't Work in ASP.NET 4.0

by Ezekiel 19. November 2010 11:09

 

I just upgraded my site from 3.5 to 4.0.  Ran into a problem with adding entries to my blog.  When saving new posts with HTML the app was blowing up.  Here is the solution.

 

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestValidationMode="2.0" />
</system.web>

Tags: , ,

ASP.NET | .NET 4.0

Breadcrumb Using LINQ to SQL, Generic Class and Recursive CTE

by Ezekiel 12. November 2010 16:23
[No text]

Tags: , , , ,

ASP.NET | C# | LINQ to SQL | SQL

Disable Submit Button When the Submit Button is Clicked

by Ezekiel 12. October 2010 07:14

 

    <script type="text/javascript"><!--
    function doSubmit(btnSubmit) {
        if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
            return false;
        }   
        btnSubmit.disabled = 'disabled';
        btnSubmit.value = 'Processing. Please wait...';
        <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>;   
    }
    //-->
    </script>

 

   <asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" CssClass="submit1" runat="server" />

 

Tags: ,

ASP.NET | Javascript

How to Get Computer Name using C#

by Ezekiel 8. October 2010 09:50

 

string machineName = System.Environment.MachineName;

Tags:

C#

Linq Query to Generic Custom List

by Ezekiel 13. September 2010 18:05

 

How to return linq to sql query in a method.

 

Generic List Method -

public static List<ProductList> GetProductsList(int? id)
{
    using (Data.DataClassesDataContext db = new Data.DataClassesDataContext())
    {
        var prod = from p in db.Products
                    where p.CJId == id
                    select new ProductList
                    {
                        ProductID = p.ProductId,
                        Name = p.Name,
                        BuyURL = p.BuyURL,
                        ProductImage = p.ImageURL,
                        Price = p.Price,
                        URL = p.URL
                    };

        return prod.Take(1000).ToList();
    }
}

 

Class -

public class ProductList
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public string BuyURL { get; set; }
    public string ProductImage { get; set; }
    public decimal? Price { get; set; }
    public string URL { get; set; }
}

 

Tags: ,

C# | LINQ to SQL

Removing Default Namespaces from an XDocument

by Ezekiel 13. September 2010 07:47

 

private static XDocument RemoveNamespace(XDocument xdoc)
{
    foreach (XElement e in xdoc.Root.DescendantsAndSelf())
    {
        if (e.Name.Namespace != XNamespace.None)
        {
            e.Name = XNamespace.None.GetName(e.Name.LocalName);
        }

        if (e.Attributes().Where(
                a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())
        {
            e.ReplaceAttributes(e.Attributes().Select(
                    a => a.IsNamespaceDeclaration ? null : a.Name.Namespace
                        != XNamespace.None ? new XAttribute(
                            XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));
        }
    }

    return xdoc;
}

Tags: , , ,

C# | LINQ to XML

Convert XMLDocument to XDocument and Search for Node using C# XPath

by Ezekiel 28. July 2010 10:34

 

XmlDocument xmlDocument = method or doc load
XDocument xDocument = XDocument.Parse(xmlDocument.OuterXml);

XElement xElement = xDocument.XPathSelectElement("parentNode/childNode/subChildNode");
           
if (xElement != null)
{
    // Do some work
}

 

Tags: , , , ,

C#

Search all Tables in a SQL Server Database for a Column

by Ezekiel 1. July 2010 10:05

 

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )

Tags:

SQL | SQL Server

Reboot or Shutdown from Remote Desktop Connection

by Ezekiel 20. June 2010 06:20

 

To open a command prompt:

1. Click Start Menu

2. Select Run

3. Type "cmd"

 

In the command prompt:

shutdown -f       (System Shutdown)

shutdown -r -f    (System Reboot)

shutdown -i -f    (Get a GUI)

shutdown -l -f    (logoff)

Tags: ,

Windows

How to Search Stored Procedures for Specific Database Table

by Ezekiel 18. June 2010 06:53

 

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%TableName%'
AND ROUTINE_TYPE='PROCEDURE'

Tags:

SQL Server

C# Mask Social Security Number

by Ezekiel 12. May 2010 15:17

 

  public static  string MaskSSN(string SSN)

        {

            if (string.IsNullOrEmpty(SSN))

                return SSN;

            SSN = Regex.Replace(SSN,@"\D",string.Empty);//SSN.Replace("-", string.Empty).Trim().Replace(" ", string.Empty).Trim();

            if (SSN.Length == 9)

                SSN = string.Format("###-##-{0}", SSN.Substring(SSN.Length - 4, 4));

            else

                SSN = string.Empty;

 

            return SSN;

        }

Tags: ,

C#

C# Get Unformatted Phone Number

by Ezekiel 12. May 2010 15:16

 

public static string  GetUnFormattedPhoneNumber(string num)

        {

            if(!string.IsNullOrEmpty(num))

            {

              num = Regex.Replace(num, @"\D", string.Empty);

            }

            return num;

            // return num.Replace("(", "").Replace(")", "").Replace("-", "");

 

        }

Tags: ,

C#

Use C# to Parse Date into Local Culture Format

by Ezekiel 1. May 2010 18:47

 

DateTime date = DateTime.Parse(originalDate, CultureInfo.CurrentCulture.DateTimeFormat);

Tags: ,

C#

Add Column or Multiple Columns to Table in SQL Server Using SQL

by Ezekiel 1. May 2010 06:10

 

ALTER TABLE tableName
ADD columnName varchar(50)

 

ALTER TABLE tableName
ADD columnName1 char(1) DEFAULT 'N' NOT NULL,
columnName2 char(1) DEFAULT 'N' NOT NULL,
columnName3 char(1) DEFAULT 'N' NOT NULL,
columnName4 char(1) DEFAULT 'N' NOT NULL,
columnName5 char(1) DEFAULT 'N' NOT NULL

Tags: ,

SQL | SQL Server

Another Installation Process is Running

by Ezekiel 19. April 2010 02:51

 

Have you ever received this message when trying to install something and the installation process errors.  If so here is what to do.

 

1. Open Task Manager.

2. Look for an application called Msiexec.exe.

3. Right click on this app and click 'End Process'.

 

Tags:

How to Search all Stored Procedures in a Database

by Ezekiel 10. April 2010 06:43

 

SELECT O.NAME, S.DEFINITION, ISR.ROUTINE_CATALOG, ISR.ROUTINE_SCHEMA,
O.TYPE AS obj_TYPE_CODE, O.TYPE_DESC AS obj_TYPE_DESCRIPTION

FROM SYS.OBJECTS AS O
INNER JOIN    SYS.SQL_MODULES AS S ON O.OBJECT_ID = S.OBJECT_ID
LEFT JOIN    SYS.SYSOBJECTS AS SO ON O.OBJECT_ID = SO.id
LEFT JOIN    INFORMATION_SCHEMA.ROUTINES ISR ON SO.NAME = ISR.ROUTINE_NAME

WHERE S.DEFINITION LIKE '%JOIN%'AND S.DEFINITION LIKE '%ON%'
ORDER BY O.TYPE,O.NAME

Tags: ,

SQL | SQL Server

How to Update Column from a Column in the same Table

by Ezekiel 10. April 2010 06:39

 

UPDATE tablename
SET ID = ID2
WHERE ID = ID

Tags: ,

SQL | SQL Server

How to Add Primary Key Cluster Using SQL Script

by Ezekiel 10. April 2010 06:35

 

ALTER TABLE TABLENAME
ADD CONSTRAINT [PK_TABLENAME]
PRIMARY KEY CLUSTERED
(
    [ID] ASC,
    [ID2] ASC
)

Tags: ,

SQL | SQL Server

Edit C# Code When in Debug Mode in Visual Studio 2008

by Ezekiel 26. February 2010 10:26

 

Ever wanted to edit code when in debug mode in VS.  If you have tried no doubt you have seen the following message.

"Changes are not allowed while code is running or if the option 'Break all processed when one process breaks' is disabled.  The option can be enabled in Tools, Options, Debugging."

 

To fix this problem do the following steps.

Tools > Options > Debugging > Edit and Continue

Uncheck Edit and Continue checkbox.  You should be able to edit when in debug mode now.

 

Tags:

Visual Studio

Can Not Drop Database Because It's Currently In Use

by Ezekiel 26. February 2010 04:10

 

Run this first:

ALTER DATABASE DatabaseName

SET SINGLE_USER

WITH ROLLBACK IMMEDIATE

GO

 

Then run this:

USE Master;

DROP DATABASE DatabaseName

GO

Tags:

SQL Server

WCF (405) Method Not Allow Error On Vista

by Ezekiel 24. February 2010 07:51

 

Here are the steps we took to solve this issue.

1. We set the application pool to classic.

2. Went to Windows setup and checked the box for digest authentication.

3. From a cmd prompt entered the following command -

"%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r

Tags:

ASP.NET

Delete User Work Space From Team Server Foundation

by Ezekiel 22. February 2010 06:21

 

tf workspace /delete ComputerName;UserName /server:http://TFSServerName:8080

Tags:

Team Server Foundation

C# Get Base URL From Address Bar

by Ezekiel 28. January 2010 16:10

 

        private string GetBaseUrl(HttpRequest request)
        {
            StringBuilder url = new StringBuilder();
           
            url.Append(request.Url.Scheme);
            url.Append("://");
            url.Append(request.Url.Host);

            if(request.Url.Port != 80)
            {
                url.Append(":");
                url.Append(request.Url.Port);
            }

            url.Append(request.ApplicationPath);

            return url.ToString();
        }

Tags: ,

C#

How to Get Website URL With Inline ASP.NET

by Ezekiel 15. January 2010 06:17

 

Use this to get the websites URL only.

<%= Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty) %>

 

Return -

URL: http://www.ezekielonline.com/Portfolio.aspx

Gets Only: http://www.ezekielonline.com

 

How to use -

<a rel="#voverlay" href="videos/engine/swf/player.swf?url=<%= Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, String.Empty) %>/videos/videos.flv">

    <img src="images/video.jpg" width="369" height="278" align="left" alt="" />

</a>

 

So this will get the URL only.  You can use through out the development process. dev, stage, live.

Tags: , ,

ASP.NET

How to Restore SQL Server Database from .bak File

by Ezekiel 23. December 2009 05:12

 

1. Open SQL Server Management Studio on your local machine.
2. Right click the Databases folder. From the pop-up menu, select New Database.
3. Enter a database name, and then click Ok.
4. Right click the new database icon. From the pop-up menu, select Tasks -> Restore -> Database.
5. Select the From Device option, and then click the browse button.
6. Click Add and navigate to the appropriate file. Click Ok.
7. In the Restore Database window, select the checkbox next to your .bak file.
8. Switch to the Options page. Select the Overwrite the existing database checkbox.
9. Click Ok.

Tags: ,

SQL Server

How to Restore SQL Server Database from .mdf File

by Ezekiel 23. December 2009 04:54

 

1. Open SQL Server Management Studio on your local machine.
2. Right click the Databases folder. From the pop-up menu, select Attach.
3. Click Add and select the appropriate .mdf file. Click Ok, and then click Ok again.
4. Verify the contents of your database, which is now active on your local machine.

Tags: ,

SQL Server

Find Control in Nested DataList, Repeater, ListView

by Ezekiel 10. December 2009 08:48

 

Have you ever had to deal with finding controls in nested Repeaters or any nested data list control?  If you haven't you will one day.  It's impossible to find the controls in the nested data list controls.  This Class and method will find any control. 

Class -

     public class MyUtility
    {
        public static Control FindControl(string id, ControlCollection col)
        {
            foreach (Control c in col)
            {
                Control child = FindControlRecursive(c, id);
                if (child != null)
                    return child;
            }
            return null;
        }

        private static Control FindControlRecursive(Control root, string id)
        {
            if (root.ID != null && root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control rc = FindControlRecursive(c, id);
                if (rc != null)
                    return rc;
            }
            return null;
        }
    }

 

Method -

        // FindControl override
        public override Control FindControl(string id)
        {
            Control bc = null;
            try
            {
                bc = base.FindControl(id);
            }
            catch (HttpException)
            {
                bc = null;
            }
            return (bc != null) ? bc : MyUtility.FindControl(id, this.Controls);
        }

Use -

      HyperLink hyperLink = (HyperLink)FindControl("controlName");

 

Tags: ,

CSS

How to Update records in DataTable

by Ezekiel 30. November 2009 05:26

 

private DataTable UpdateDataTable(DataTable dt)
{
    DataRow dr;
               
    for(int i = 0; i < dt.Rows.Count; i++)
    {
        dr = dt.Rows[i]; // gives you the specific row...
        dr["columnName"] = dr["columnName"] + " Add Text";
  
       
        dr.AcceptChanges();
    }

    dt.AcceptChanges();

    return dt;
}

Tags:

C#

Fixed Position Background Image Using CSS

by Ezekiel 26. November 2009 05:17

 

CSS -

body
{
    background: #fff url('images/imagename.jpg') 0px 0px no-repeat-y fixed;
    font-family: arial, sans-serif
}

.wrapper {
    background: #fff url('images/imagename.jpg') 0 0 no-repeat fixed;
}

 

HTML -

<body>

    <div class="wrapper">


    </div>

</body>

Tags: , ,

CSS | HTML

Using XDocument and XElement to Exact XML Data

by Ezekiel 17. November 2009 06:26


XML example data:

<userDetails>
   <SPN>
      <AccountID>123456</AccountID>
   </SPN>
</userDetails>

 

C#:

XDocument xmldoc = XDocument.Load(new StringReader(xml.ToString().Trim()));

XElement xAccountID = xmldoc.XPathSelectElement("/userDetails/SPN/AccountID");

string AccountID = "";

if (xAccountID != null)
   AccountID = xAccountID.Value;

 

Tags: ,

C#

Populate an ASP.NET DropDownList Control

by Ezekiel 4. November 2009 10:11

 

HTML -

<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>

 

C# -

// Clear all items in drop down
ddl.Items.Clear();

// Populate the status filter
ddl.DataTextField = "dataFieldToShowToPublic";
ddl.DataValueField = "dataFieldToPassToMethod";

// Call to your data layer
ddl.DataSource = sqlObject.GetDropDownData();
ddl.DataBind();
           
// Blank item at the top of the list
ddl.Items.Insert(0, new ListItem("--", ""));

 

Data Layer Method -

public DataTable GetDropDownData()
{
    SqlConnection conn = GetConnection();
    SqlCommand cmd = conn.CreateCommand();
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);

    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM TableName ORDER BY dataField";
    da.Fill(ds);

    conn.Close();
    return ds.Tables[0];
}

 

 

Tags: , , ,

ASP.NET | C# | SQL

Visual Studio 2008 Data Connections

by Ezekiel 2. November 2009 16:07

 

I was trying to add a SQL Server to the data connection and run into this error.

Microfsoft.SqlServer.Management.sdk.sfc can not be found

 

Resolution:

1. Download the Microsoft SQL Server 2008 Management Objects in the following URL:

http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0x409

2. Install it in the machine

3. Restart Visual Web Developer

Tags:

Visual Studio

Visual Studio Hotkeys

by Ezekiel 27. October 2009 06:27

 

I love using hotkeys.  Here are some of the hotkeys I used the most.

 

ctrl + c = copy
ctrl + v = paste
ctrl + x = cut
ctrl + a = select all
ctrl + k + c = comment out
ctrl + k + u = uncomment
ctrl + m + o = closes all methods
ctrl + m + l = open all methods
ctrl + k + x = insert snipplet
F1 = help
F5 = run application
ctrl + F5 = run application with debug
F6 = build solution
shift + F6 = build project
ctrl + Home = top of the file
ctrl + End = end of the file
F7 = switch from ASP.NET side to C# side
shift + F7 = switch to design
F9 = insert new break point
F10 = step over method
F11 = step into method
F12 = go to method definition
shift + F12 = show where method is used
ctrl + - = go back to method use

Tags:

Visual Studio

SQL LEFT OUTER JOIN

by Ezekiel 27. October 2009 03:45

 

For a long time I had a problem understanding how to use a LEFT OUTER JOIN in my SQL statement.  A lot of explanations out there are hard to understand.  So a LEFT OUTER JOIN works by joining the left side of the equals sign to the right side.  If there isn't a record to tie it to will not effect your return. 

For example:

DECLARE @promotionKey varchar(100)
SET @promotionKey = 'PromotionName'

SELECT TOP 1 pl.promotionID  
   FROM Promotions p
   JOIN PromotionLocales pl ON p.promotionID = pl.promotionID
   JOIN PromotionCodes pc ON pl.promotionID = pc.promotionID
   LEFT OUTER JOIN PromotionCourseRequirements pcr ON pcr.promotionID = pl.promotionID
 
 WHERE p.promotionKey = @promotionKey

Here I'm looking for a record in table PromotionCourseRequirements which has the same promotionID as in table PromotionLocales.  If there isn't one it will not effect the returned records.

 

 

Tags:

SQL

Capitalize First and Last Name Using SQL

by Ezekiel 23. October 2009 10:35

 

(UPPER(LEFT(u.firstName, 1)) + LOWER(SUBSTRING(u.firstName, 2, LEN(u.firstName)))) AS firstName, (UPPER(LEFT(u.firstName, 1)) + LOWER(SUBSTRING(u.firstName, 2, LEN(u.firstName))) + ' ' + UPPER(LEFT(u.lastName, 1)) + LOWER(SUBSTRING(u.lastName, 2, LEN(u.lastName)))) AS name

Tags:

SQL

ImageButton OnClick Event Fires When Enter is Clicked

by Ezekiel 23. October 2009 08:09

 

I have this pagination control.  The problem was when the user entered a page number in the textbox it would fire the OnClick event of the first ImageButton.  This would only happen in FireFox.  Worked fine in IE.  To prevent this from happening I dropped an asp:button on the form in a panel.  Set the style visibility to hidden so the button wouldn't show and set the DefaultButton panel property to the hidden button.  Works great!


<asp:Panel ID="pnlPaginationCtrl" DefaultButton="btnPageNum" runat="server" Visible="true" CssClass="m_prevnext">
    <table>
        <tr>
            <td>
                <asp:ImageButton ID="imgBtnFirstPage" runat="server" AlternateText="|&lt;"
                    onclick="imgBtnFirstPage_Click" ImageUrl="~/Images/reporting/Beginning20x20.png" CausesValidation="false" />
                   
                <asp:ImageButton ID="imgBtnPrevPage" runat="server" AlternateText="&lt;&lt;" CausesValidation="false"
                    onclick="imgBtnPrevPage_Click" ImageUrl="~/Images/reporting/Back20x20.png" />
            </td>
            <td>      
                <asp:TextBox ID="tbPage" runat="server" AutoPostBack="True"
                    OnTextChanged="tbPage_TextChanged" Width="30px" CssClass="tbpadding"></asp:TextBox>
                   
                <asp:Button ID="btnPageNum" runat="server" style="visibility:hidden;display:none;" />
                   
                <asp:RangeValidator ID="rvPage" runat="server" ControlToValidate="tbPage" ErrorMessage="page is to big" MinimumValue="1" MaximumValue="25" Type="Integer" Display="None"></asp:RangeValidator>
                   
                <cc1:FilteredTextBoxExtender ID="tbPage_FilteredTextBoxExtender"
                    runat="server" Enabled="True" FilterType="Numbers" TargetControlID="tbPage" />

                <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="rvPage" />
               
                of&nbsp;<asp:Label ID="lblNumOfPages" runat="server" Text="##"></asp:Label>
            </td>
            <td>        
                <asp:ImageButton ID="imgBtnNextPage" runat="server" CausesValidation="false"
                    onclick="imgBtnnextPage_Click" AlternateText="&gt;&gt;"
                    ImageUrl="~/Images/reporting/next.png" />
                   
                <asp:ImageButton ID="imgBtnLastPage" runat="server" CausesValidation="false"
                    AlternateText="&gt;|" ImageUrl="~/Images/reporting/end.png"
                    onclick="imgBtnLastPage_Click" />
            </td>
        </tr>
    </table>    
</asp:Panel>

Tags:

ASP.NET

Wrap Text Around Image Using CSS

by Ezekiel 22. October 2009 10:54

 

HTML -

<asp:Image ID="Image1" runat="server" CssClass="featuredPic" />
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text


CSS -

.featuredPic{
 border: double rgb(183,183,183);
 border-width: 1px;
 padding-left: 2px;
 padding-right: 2px;
 padding-top: 2px;
 padding-bottom: 2px;
 margin-right: 11px;
 float: left;
}

 

Tags: ,

CSS | HTML

Credit Card Processing

by Ezekiel 19. October 2009 09:47

 

Populate Credit Card Year Expiration -

ddlExpYear.Items.Clear();

for (int i = DateTime.Now.Year; i <= DateTime.Now.Year + 11; i++)
 ddlExpYear.Items.Add(new ListItem(i.ToString(), i.ToString()));

// Blank item
ddlExpYear.Items.Insert(0, new ListItem("--", ""));

 

ASP.NET Credit Card Number Validator -

<asp:RegularExpressionValidator ID="revCardNumber" ControlToValidate="cardNumber" ValidationExpression="^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$" ErrorMessage="Please enter a valid credit card number." Display="Dynamic" cssClass="error" runat="server" SetFocusOnError="True"></asp:RegularExpressionValidator>

Tags: , ,

C#

HTML Codes

by Ezekiel 27. September 2009 17:14

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F

!
"
#
$
%
&
'
(
)
*
+
,
-
.
/
&#32;
&#33;
&#34;
&#35;
&#36;
&#37;
&#38;
&#39;
&#40;
&#41;
&#42;
&#43;
&#44;
&#45;
&#46;
&#47;


&quot;



&amp;









space
exclamation point
double quotes
number sign
dollar sign
percent sign
ampersand
single quote
opening parenthesis
closing parenthesis
asterisk
plus sign
comma
minus sign - hyphen
period
slash

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
&#48;
&#49;
&#50;
&#51;
&#52;
&#53;
&#54;
&#55;
&#56;
&#57;
&#58;
&#59;
&#60;
&#61;
&#62;
&#63;












&lt;

&gt;

zero
one
two
three
four
five
six
seven
eight
nine
colon
semicolon
less than sign
equal sign
greater than sign
question mark

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
&#64;
&#65;
&#66;
&#67;
&#68;
&#69;
&#70;
&#71;
&#72;
&#73;
&#74;
&#75;
&#76;
&#77;
&#78;
&#79;
















at symbol















 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_
&#80;
&#81;
&#82;
&#83;
&#84;
&#85;
&#86;
&#87;
&#88;
&#89;
&#90;
&#91;
&#92;
&#93;
&#94;
&#95;



























opening bracket
backslash
closing bracket
caret - circumflex
underscore

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
`
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
&#96;
&#97;
&#98;
&#99;
&#100;
&#101;
&#102;
&#103;
&#104;
&#105;
&#106;
&#107;
&#108;
&#109;
&#110;
&#111;
















grave accent















 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~

&#112;
&#113;
&#114;
&#115;
&#116;
&#117;
&#118;
&#119;
&#120;
&#121;
&#122;
&#123;
&#124;
&#125;
&#126;




























opening brace
vertical bar
closing brace
equivalency sign - tilde
(not defined in HTML 4 standard)

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------------------
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
















































(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------------------
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
















































(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)
(not defined in HTML 4 standard)

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-----------------------------------------------------------------------------------------------------------
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
 
¡
¢
£
¤
¥
¦
§
¨
©
ª
«
¬
­
®
¯
&#160;
&#161;
&#162;
&#163;
&#164;
&#165;
&#166;
&#167;
&#168;
&#169;
&#170;
&#171;
&#172;
&#173;
&#174;
&#175;
&nbsp;
&iexcl;
&cent;
&pound;
&curren;
&yen;
&brvbar;
&sect;
&uml;
&copy;
&ordf;
&laquo;
&not;
&shy;
&reg;
&macr;
non-breaking space
inverted exclamation mark
cent sign
pound sign
currency sign
yen sign
broken vertical bar
section sign
spacing diaeresis - umlaut
copyright sign
feminine ordinal indicator
left double angle quotes
not sign
soft hyphen
registered trade mark sign
spacing macron - overline

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
--------------------------------------------------------------------------------------------------------------
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF
°
±
²
³
´
µ

·
¸
¹
º
»
¼
½
¾
¿
&#176;
&#177;
&#178;
&#179;
&#180;
&#181;
&#182;
&#183;
&#184;
&#185;
&#186;
&#187;
&#188;
&#189;
&#190;
&#191;
&deg;
&plusmn;
&sup2;
&sup3;
&acute;
&micro;
&para;
&middot;
&cedil;
&sup1;
&ordm;
&raquo;
&frac14;
&frac12;
&frac34;
&iquest;
degree sign
plus-or-minus sign
superscript two - squared
superscript three - cubed
acute accent - spacing acute
micro sign
pilcrow sign - paragraph sign
middle dot - Georgian comma
spacing cedilla
superscript one
masculine ordinal indicator
right double angle quotes
fraction one quarter
fraction one half
fraction three quarters
inverted question mark

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-------------------------------------------------------------------------------------------------------------------
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
À
Á
Â
Ã
Ä
Å
Æ
Ç
È
É
Ê
Ë
Ì
Í
Î
Ï
&#192;
&#193;
&#194;
&#195;
&#196;
&#197;
&#198;
&#199;
&#200;
&#201;
&#202;
&#203;
&#204;
&#205;
&#206;
&#207;
&Agrave;
&Aacute;
&Acirc;
&Atilde;
&Auml;
&Aring;
&AElig;
&Ccedil;
&Egrave;
&Eacute;
&Ecirc;
&Euml;
&Igrave;
&Iacute;
&Icirc;
&Iuml;
latin capital letter A with grave
latin capital letter A with acute
latin capital letter A with circumflex
latin capital letter A with tilde
latin capital letter A with diaeresis
latin capital letter A with ring above
latin capital letter AE
latin capital letter C with cedilla
latin capital letter E with grave
latin capital letter E with acute
latin capital letter E with circumflex
latin capital letter E with diaeresis
latin capital letter I with grave
latin capital letter I with acute
latin capital letter I with circumflex
latin capital letter I with diaeresis

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
-------------------------------------------------------------------------------------------------------------------
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
Ð
Ñ
Ò
Ó
Ô
Õ
Ö
×
Ø
Ù
Ú
Û
Ü
Ý
Þ
ß
&#208;
&#209;
&#210;
&#211;
&#212;
&#213;
&#214;
&#215;
&#216;
&#217;
&#218;
&#219;
&#220;
&#221;
&#222;
&#223;
&ETH;
&Ntilde;
&Ograve;
&Oacute;
&Ocirc;
&Otilde;
&Ouml;
&times;
&Oslash;
&Ugrave;
&Uacute;
&Ucirc;
&Uuml;
&Yacute;
&THORN;
&szlig;
latin capital letter ETH
latin capital letter N with tilde
latin capital letter O with grave
latin capital letter O with acute
latin capital letter O with circumflex
latin capital letter O with tilde
latin capital letter O with diaeresis
multiplication sign
latin capital letter O with slash
latin capital letter U with grave
latin capital letter U with acute
latin capital letter U with circumflex
latin capital letter U with diaeresis
latin capital letter Y with acute
latin capital letter THORN
latin small letter sharp s - ess-zed

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
------------------------------------------------------------------------------------------------------------------
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
à
á
â
ã
ä
å
æ
ç
è
é
ê
ë
ì
í
î
ï
&#224;
&#225;
&#226;
&#227;
&#228;
&#229;
&#230;
&#231;
&#232;
&#233;
&#234;
&#235;
&#236;
&#237;
&#238;
&#239;
&agrave;
&aacute;
&acirc;
&atilde;
&auml;
&aring;
&aelig;
&ccedil;
&egrave;
&eacute;
&ecirc;
&euml;
&igrave;
&iacute;
&icirc;
&iuml;
latin small letter a with grave
latin small letter a with acute
latin small letter a with circumflex
latin small letter a with tilde
latin small letter a with diaeresis
latin small letter a with ring above
latin small letter ae
latin small letter c with cedilla
latin small letter e with grave
latin small letter e with acute
latin small letter e with circumflex
latin small letter e with diaeresis
latin small letter i with grave
latin small letter i with acute
latin small letter i with circumflex
latin small letter i with diaeresis

 

 

 

 

ASCII   HTML HTML  
Dec Hex Symbol Number Name Description
------------------------------------------------------------------------------------------------------------------
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
ð
ñ
ò
ó
ô
õ
ö
÷
ø
ù
ú
û
ü
ý
þ
ÿ
&#240;
&#241;
&#242;
&#243;
&#244;
&#245;
&#246;
&#247;
&#248;
&#249;
&#250;
&#251;
&#252;
&#253;
&#254;
&#255;
&eth;
&ntilde;
&ograve;
&oacute;
&ocirc;
&otilde;
&ouml;
&divide;
&oslash;
&ugrave;
&uacute;
&ucirc;
&uuml;
&yacute;
&thorn;
&yuml;
latin small letter eth
latin small letter n with tilde
latin small letter o with grave
latin small letter o with acute
latin small letter o with circumflex
latin small letter o with tilde
latin small letter o with diaeresis
division sign
latin small letter o with slash
latin small letter u with grave
latin small letter u with acute
latin small letter u with circumflex
latin small letter u with diaeresis
latin small letter y with acute
latin small letter thorn
latin small letter y with diaeresis

     

    HTML HTML  
Dec Hex Symbol Number Name Description
------------------------------------------------------------------------------------------------------------------
338
339
352
353
376
402
152
153
160
161
178
192
Œ
œ
Š
š
Ÿ
ƒ
&#338;
&#339;
&#352;
&#353;
&#376;
&#402;






latin capital letter OE
latin small letter oe
latin capital letter S with caron
latin small letter s with caron
latin capital letter Y with diaeresis
latin small f with hook - function
     
    HTML HTML  
Dec Hex Symbol Number Name Description
------------------------------------------------------------------------------------------------------------------
8211
8212
8216
8217
8218
8220
8221
8222
8224
8225
8226
8230
8240
8364
8482
2013
2014
2018
2019
201A
201C
201D
201E
2020
2021
2022
2026
2030
20AC
2122















&#8211;
&#8212;
&#8216;
&#8217;
&#8218;
&#8220;
&#8221;
&#8222;
&#8224;
&#8225;
&#8226;
&#8230;
&#8240;
&#8364;
&#8482;













&euro;

en dash
em dash
left single quotation mark
right single quotation mark
single low-9 quotation mark
left double quotation mark
right double quotation mark
double low-9 quotation mark
dagger
double dagger
bullet
horizontal ellipsis
per thousand sign
euro sign
trade mark sign

Tags:

HTML | ASCII

RecentPosts