Friday, May 31, 2013

How to update BLOB field in SQL Server?

UPDATE myTable
SET theBlobField =
(SELECT BulkColumn FROM OPENROWSET (BULK 'C:\logo.png, SINGLE_BLOB) a)
WHERE [ID] = 1

How to save binary (BLOB) field into local file from SQL Server database by SQL?



DECLARE @SQLIMG VARCHAR(MAX),
 @IMG_PATH VARBINARY(MAX),
 @TIMESTAMP VARCHAR(MAX),
 @ObjectToken INT

DECLARE IMGPATH CURSOR FAST_FORWARD FOR 
  SELECT csl_CompanyLogo from mlm_CSCompanySettingsLocalizations
  
OPEN IMGPATH 

FETCH NEXT FROM IMGPATH INTO @IMG_PATH 

WHILE @@FETCH_STATUS = 0
 BEGIN
  SET @TIMESTAMP = 'd:\' + replace(replace(replace(replace(convert(varchar,getdate(),121),'-',''),':',''),'.',''),' ','') + '.bmp'

  PRINT @TIMESTAMP
  PRINT @SQLIMG

  EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
  EXEC sp_OASetProperty @ObjectToken, 'Type', 1
  EXEC sp_OAMethod @ObjectToken, 'Open'
  EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @IMG_PATH
  EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @TIMESTAMP, 2
  EXEC sp_OAMethod @ObjectToken, 'Close'
  EXEC sp_OADestroy @ObjectToken

  FETCH NEXT FROM IMGPATH INTO @IMG_PATH 
 END 

CLOSE IMGPATH
DEALLOCATE IMGPATH


Reference:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101754

Thursday, May 30, 2013

How to solve "null reference exception" problem when turn off ProxyCreationEnabled in Code first Entity framework?

If turn on lazy loading in entity framework by:
Configuration.ProxyCreationEnabled = false;
Will get null reference exception problem when try to get navigation properties.

Need to do eagerly loading for navigation property by include clause
using (var context = new BloggingContext())
{
    // Load all blogs and related posts
    var blogs1 = context.Blogs
                          .Include(b => b.Posts)
                          .ToList();

}

Inheritance in Entity Framework Code First

public abstract class Person
{
     public int PersonID { get; set; }
     public string Name { get; set; }
}
 
public class StaffMember : Person
{
     public string BadgeNumber { get; set; }
     [ForeignKey("StaffMemberID")]
     public virtual ICollection Appointments { get; set; }
}
 
public class Client : Person
{
     [ForeignKey("ClientID")]
     public virtual ICollection Appointments { get; set; }
}
 

public class MyContext : DbContext
{
     public DbSet People { get; set; }
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
          base.OnModelCreating(modelBuilder);
     }
 
     public void Seed(MyContext context)
     {
          Client c1 = new Client { Name = "Steve Client" };
          StaffMember sm1 = new StaffMember { Name = "Staff 1", BadgeNumber = "1234" };
          StaffMember sm2 = new StaffMember { Name = "Staff 2", BadgeNumber = "5678" };
 
          context.People.Add(c1);
          context.People.Add(sm1);

          context.SaveChanges();
      }
 
      public MyContext()
      {
           Database.SetInitializer(new DropCreateDatabaseAlways());
           this.Seed(this);
      }
}


http://sgordondeveloper.blogspot.ca/2013/02/model-inheritance-with-relationship-in.html

Friday, May 24, 2013

What's the difference between IFrame and Frameset?

Frameset is dead and long live iframe :)
Frameset replace body elment. And ifeame can be anywhere in the body. Also frameset is NOT supported in HTML 5

http://www.w3.org/TR/html401/frameset.dtd

Wednesday, May 22, 2013

How to insert BLOB data into database by SQL script?

SELECT ThumbnailPhoto.*, null, null, N'tricycle_pink.gif'
FROM OPENROWSET
(BULK 'c:\images\tricycle.jpg', SINGLE_BLOB) ThumbnailPhoto

Tuesday, May 21, 2013

How to add jQuery reference into ASP.NET MVC 4 project?



@Scripts.Render("~/bundles/jquery")

How to solve "Access is denied" problem in new ASP.NET MVC 4 project?

- Press F4 on the MVC project to open project property window
- Change "Windows Authentication" from "Disabled" to "Enabled"


Error message

Server Error in '/' Application.
Access is denied.


Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.

Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server's administrator for additional assistance.

Thursday, May 16, 2013

How to get visitor's MAC address in ASP.NET?


No, you can't. MAC address is not included in request IP header.

Monday, May 13, 2013

How to login into ASP.NET webforms site by HttpWebRequest

http://odetocode.com/articles/162.aspx

private void Button5_Click(object sender, System.EventArgs e)
{
// first, request the login form to get the viewstate value
HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream()
);
string responseData = responseReader.ReadToEnd();
responseReader.Close();

// extract the viewstate value and build out POST data
string viewState = ExtractViewState(responseData);
string postData =
String.Format(
"__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login",
viewState, USERNAME, PASSWORD
);

// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();

// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;

// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();

// we don't need the contents of the response, just the cookie it issues
webRequest.GetResponse().Close();

// now we can send out cookie along with a request for the protected page
webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

// and read the response
responseData = responseReader.ReadToEnd();
responseReader.Close();

Response.Write(responseData);
}

Friday, May 10, 2013

How to add static html in ASP.NET MVC site?

Need to change routing setting in Global.asax.cs file like following:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.html/{*pathInfo}");
        }

Thursday, May 9, 2013

How to change URL without reloading current page by Javascript

window.history.pushState('page2', 'Title', '/page2');

Tuesday, May 7, 2013

What is the difference between Html button and input type=button?


Almost same, but button with more rendering abilities.


Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.
The Button Element - W3C

References:
http://stackoverflow.com/questions/469059/button-vs-input-type-button-which-to-use
http://web.archive.org/web/20110721191046/http://particletree.com/features/rediscovering-the-button-element/

Friday, May 3, 2013

How to extract text from html by HtmlAgilityPack?


            string htmlstring ="

adsasd

"; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(htmlstring); foreach (var script in doc.DocumentNode.Descendants("script").ToArray()) script.Remove(); foreach (var style in doc.DocumentNode.Descendants("style").ToArray()) style.Remove(); string ExtractedText = doc.DocumentNode.InnerText;

How to change EDMX connection string at runtime in Entity Framework?

Call constructor with connection string parameter like:
var db = new dbContext(connectionstring);

How to use MVC, Webforms and Web API in same ASP.NET project?

http://msdn.microsoft.com/en-us/magazine/dn198242.aspx


Leverage Multiple Code Frameworks with One ASP.NE

Remove Unwanted HTTP Response Headers

http://blogs.msdn.com/b/varunm/archive/2013/04/23/remove-unwanted-http-response-headers.aspx

Server - Specifies web server version.
X-Powered-By - Indicates that the website is "powered by ASP.NET."
X-AspNet-Version - Specifies the version of ASP.NET used.

Thursday, May 2, 2013

How to change cursor when loading page or selecting item from dropdownlist in ASP.NET webform?

Goto master page
Add two events in body tag like following
<body onbeforeunload="document.body.style.cursor = 'wait';" onunload="document.body.style.cursor = 'default';">

Use a Software Bug to Win Video Poker? That’s a Federal Hacking Case

http://www.wired.com/threatlevel/2013/05/game-king/all/