Diwakar's Blog

http://diwakarko.blogspot.com (दिवाकरको ब्लग)

Nepali Unicode Converter Fantasy Himali to Nepali Unicode

5 comments
Nepali Unicode Conversion Tools For Fantasy Himali to Nepali Unicode, easy way to convert Fantasy Himali tt font Text to Nepali Unicode Text.
Visit demo Site click here

5 comments :

Post a Comment

Apache Authentication in htaccess

No comments

Require password for 1 file only

<files login.php>
Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthType Basic
AuthUserFile /web/askapache.com/.htpasswd
Require valid-user
</Files>

Protect multiple files:

<FilesMatch "^(exec|env|doit|phpinfo|w).*$">
Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthUserFile /.htpasswd
AuthType basic
Require valid-user
</FilesMatch>

Using the Apache Allow Directive in htaccess

network/netmask pair

Order deny,allow
Deny from all
Allow from 10.1.0.0/255.255.0.0

IP address

Order deny,allow
Deny from all
Allow from 10.1.2.3

More than 1 IP address

Order deny,allow
Deny from all
Allow from 192.168.1.104 192.168.1.205

Partial IP addresses, first 1 to 3 bytes of IP, for subnet restriction

Order deny,allow
Deny from all
Allow from 10.1
Allow from 10 172.20 192.168.2

network/nnn CIDR specification

Order deny,allow
Deny from all
Allow from 10.1.0.0/16

IPv6 addresses and subnets

Order deny,allow
Deny from all
Allow from 2001:db8::a00:20ff:fea7:ccea
Allow from 2001:db8::a00:20ff:fea7:ccea/10

Deny subdomains

Order Allow,Deny
Allow from apache.org
Deny from wireshark.apache.org

Allow from IP without password prompt, and also allow from any address with password prompt

Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthUserFile /web/askapache.com/.htpasswd
AuthType Basic
Require valid-user
Allow from 172.17.10.1
Satisfy Any

Skeleton .htaccess file to start with

I use this when I start a new site, and uncomment or delete parts of the file depending on the sites needs
Ultimate htaccess file sample
#
#            DEFAULT SETTINGS
#
Options +ExecCGI -Indexes
DirectoryIndex index.php index.html index.htm
 
ErrorDocument 400 /cgi-bin/error.php
ErrorDocument 401 /cgi-bin/error.php
ErrorDocument 403 /cgi-bin/forbidden.cgi
ErrorDocument 404 /404.html
ErrorDocument 405 /cgi-bin/error.php
ErrorDocument 406 /cgi-bin/error.php
ErrorDocument 409 /cgi-bin/error.php
ErrorDocument 413 /cgi-bin/error.php
ErrorDocument 414 /cgi-bin/error.php
ErrorDocument 500 /cgi-bin/error.php
ErrorDocument 501 /cgi-bin/error.php
 
### DEFAULTS
ServerSignature Off
 
AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf
AddType image/x-icon .ico
 
AddDefaultCharset UTF-8
AddLanguage en-US .html .htm .txt .xml .php
 
SetEnv TZ America/Indianapolis
SetEnv SERVER_ADMIN webmaster@askapache.com
 
### PHPINI-CGI
#AddHandler php-cgi .php
#Action php-cgi /cgi-bin/php5.cgi
 
### FAST-CGI
#AddHandler fastcgi-script .fcg .fcgi .fpl
#AddHandler php5-fastcgi .php
#Action php5-fastcgi /cgi-bin/fastcgi.fcgi
 
#
#           HEADERS and CACHING
#
# 1 YEAR
<FilesMatch ".(flv|ico|pdf)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
 
# 1 WEEK
<FilesMatch ".(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
 
# 3 HOUR
<FilesMatch ".(txt|xml|js|css)$">
Header set Cache-Control "max-age=10800"
</FilesMatch>
 
# 1 MIN
<FilesMatch ".(html|htm|php)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
Header set P3P "policyref="/w3c/p3p.xml", CP="NOI DSP COR NID CUR ADM DEV OUR BUS""
Header set imagetoolbar "no"
</FilesMatch>
 
#
#          REWRITES AND REDIRECTS
#
### SEO REDIRECTS
#Redirect 301 /ssl-ns.html /2006/htaccess/apache-ssl-in-htaccess-examples.html
#Redirect 301 /ht.tml
#Redirect 301 /index.html /
#RedirectMatch 301 /2006/htaccess-forum/(.*) /2006/htaccess/$1
#RedirectMatch 301 /(.*)rfc2616(.*) http://rfc.askapache.com/rfc2616/rfc2616.html
#RedirectMatch 301 /phpmanual(.*) /manual/en/$1
 
### REWRITES
RewriteEngine On
RewriteBase /
 
### WORDPRESS
#<ifModule mod_rewrite.c>
#RewriteEngine On
#RewriteBase /
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule . /index.php [L]
#</ifModule>
 
### REQUIRE WWW
#RewriteCond %{HTTP_HOST} !^www.askapache.com$ [NC]
#RewriteRule ^(.*)$ /$1 [R=301,L]
 
### STOP LOOP CODE
#RewriteCond %{ENV:REDIRECT_STATUS} 200
#RewriteRule ^.*$ - [L]
 
### REDIRECT BLOG FEED TO FEEDBURNER
#RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator|Recent) [NC]
#RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]
 
### BLOCK WGET
#RewriteCond %{HTTP_USER_AGENT} ^Wget.* [NC]
#RewriteRule .* /cgi-bin/forbidden.cgi [L]
 
#
#           AUTHENTICATION
#
### BASIC PASSWORD PROTECTION
#AuthName "Prompt"
#AuthUserFile /web/askapache.com/.htpasswd
#AuthType basic
#Require valid-user
 
### UNDER CONSTRUCTION PROTECTION
#AuthName "Under Development"
#AuthUserFile /web/askapache.com/.htpasswd
#AuthType basic
#Require valid-user
#Order Deny,Allow
#Deny from all
#Allow from 23.23.23.1 w3.org googlebot.com google.com google-analytics.com
#Satisfy Any

No comments :

Post a Comment

Auto Load and Refresh Div Using jQuery/Ajax & PHP/MySQL

1 comment
Have you seen this Twitter Search and Facebook shows most recent tweets/posts count from the database every 10 seconds on top of the page. I had developed like this with jQuery and Ajax. It's simple just 5 lines of code

Index.php
 



load.php



1 comment :

Post a Comment

Deploying an ASP.NET Web Application to a Windows Azure Web Site

No comments
Source: http://www.windowsazure.com/en-us/develop/net/tutorials/get-started/

This tutorial shows how to deploy an ASP.NET web application to a Windows Azure Web Site by using the Publish Web wizard in Visual Studio 2012 or Visual Studio 2012 for Web Express. If you prefer, you can follow the tutorial steps by using Visual Studio 2010 or Visual Web Developer Express 2010.
You can open a Windows Azure account for free, and if you don't already have Visual Studio 2012, the SDK automatically installs Visual Studio 2012 for Web Express. So you can start developing for Windows Azure entirely for free.
This tutorial assumes that you have no prior experience using Windows Azure. On completing this tutorial, you'll have a simple web application up and running in the cloud.
You'll learn:
  • How to enable your machine for Windows Azure development by installing the Windows Azure SDK.
  • How to create a Visual Studio ASP.NET MVC 4 project and publish it to a Windows Azure Web Site.
The following illustration shows the completed application:
Web site example
Note To complete this tutorial, you need a Windows Azure account that has the Windows Azure Web Sites feature enabled. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Windows Azure Free Trial.

Tutorial segments

  1. Set up the development environment
  2. Create a web site in Windows Azure
  3. Create an ASP.NET MVC 4 application
  4. Deploy the application to Windows Azure
  5. Next steps

Set up the development environment

To start, set up your development environment by installing the Windows Azure SDK for the .NET Framework.
  1. To install the Windows Azure SDK for .NET, click the link that corresponds to the version of Visual Studio you are using. If you don't have Visual Studio installed yet, use the Visual Studio 2012 link.
    Windows Azure SDK for Visual Studio 2012
    Windows Azure SDK for Visual Studio 2010
  2. When you are prompted to run or save the installation executable, click Run.
  3. In the Web Platform Installer window, click Install and proceed with the installation.
    Web Platform Installer - Windows Azure SDK for .NET
  4. If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, install MVC 4.
When the installation is complete, you have everything necessary to start developing.

Create a web site

The next step is to create the Windows Azure web site.
  1. In the Windows Azure Management Portal, click Web Sites, and then click New.
    New web site
  2. Click Quick Create.
    Quick create
  3. In the Create Web Site step of the wizard, enter a string in the URL box to use as the unique URL for your application.
    The complete URL will consist of what you enter here plus the suffix that you see next to the text box. The illustration shows example1, but if someone has already taken that string for a URL, you need to enter a different value.
  4. In the Region drop-down list, choose the region that is closest to you.
    This setting specifies which data center your web site will run in.
  5. Click the Create Web Site arrow.
    Create a new web site
    The Management Portal returns to the Web Sites page, and the Status column shows that the site is being created. After a while (typically less than a minute), the Status column shows that the site was successfully created. In the navigation bar at the left, the number of sites you have in your account appears next to the Web Sites icon.
    Web Sites page of Management Portal, web site created

Create an ASP.NET MVC 4 application

You have created a Windows Azure Web Site, but there is no content in it yet. Your next step is to create the Visual Studio web application project that you'll publish to Windows Azure.

Create the project

  1. Start Visual Studio 2012 or Visual Studio 2012 for Web Express.
  2. From the File menu, click New, and then click Project.
    New Project in File menu
  3. In the New Project dialog box, expand C# and select Web under Installed Templates, and then select ASP.NET MVC 4 Web Application.
  4. Ensure that .NET Framework 4.5 is selected as the target framework.
  5. Name the application MyExample and click OK.
    New Project dialog box
  6. In the New ASP.NET MVC 4 Project dialog box, select the Internet Application template and click OK.
    New ASP.NET MVC 4 Project dialog box

Run the application locally

  1. Press CTRL+F5 to run the application. The application home page appears in the default browser.
    Web site running locally
This is all you need to do to create a simple application that you'll deploy to Windows Azure.

Deploy the application to Windows Azure

  1. In Visual Studio, right-click the project in Solution Explorer and select Publish from the context menu.
    Publish in project context menu
    The Publish Web wizard opens.
  2. In the Profile tab of the Publish Web wizard, click Import.
    Import publish settings The Import Publish Profile dialog box appears.
  3. If you have not previously added your Windows Azure subscription in Visual Studio, perform the following steps. In these steps you add your subscription so that the drop-down list under Import from a Windows Azure web site will include your web site.
    a. In the Import Publish Profile dialog box, click Import from a Windows Azure web site, and then click Add Windows Azure subscription.
    add Windows Azure subscription
    b. In the Import Windows Azure Subscriptions dialog box, click Download subscription file.
    download subscription file
    c. In your browser window, save the .publishsettings file.
    download .publishsettings file
    Security Note The .publishsettings file contains your credentials (unencoded) that are used to administer your Windows Azure subscriptions and services. The security best practice for this file is to store it temporarily outside your source directories (for example in the Libraries\Documents folder), and then delete it once the import has completed. A malicious user who gains access to the .publishsettings file can edit, create, and delete your Windows Azure services.
    d. In the Import Windows Azure Subscriptions dialog box, click Browse and navigate to the .publishsettings file.
    download sub
    e. Click Import.
    import
  4. In the Import Publish Profile dialog box, select Import from a Windows Azure web site, select your web site from the drop-down list, and then click OK.
    Import Publish Profile
  5. In the Connection tab, click Validate Connection to make sure that the settings are correct.
    Validate connection
  6. When the connection has been validated, a green check mark is shown next to the Validate Connection button. Click Next.
    Successfully validated connection
  7. In the Settings tab, uncheck Use this connection string at runtime option, since this application is not using a database. You can accept the default settings for the remaining items on this page. You are deploying a Release build configuration and you don't need to delete files at the destination server, precompile the application, or exclude files in the App_Data folder.
    Click Next.
    Settings tab
  8. In the Preview tab, click Start Preview.
    StartPreview button in the Preview tab
    The tab displays a list of the files that will be copied to the server. Displaying the preview isn't required to publish the application but is a useful function to be aware of. In this case, you don't need to do anything with the list of files that is displayed.
    StartPreview file output
  9. Click Publish.
    Visual Studio begins the process of copying the files to the Windows Azure server.
  10. The Output window shows what deployment actions were taken and reports successful completion of the deployment.
    Output window reporting successful deployment
  11. Upon successful deployment, the default browser automatically opens to the URL of the deployed web site.
    The application you created is now running in the cloud.
    Web site running in Windows Azure

Next steps

In this tutorial, you've seen how to deploy a simple web application to a Windows Azure Web Site. Other resources are available to show you how to manage, scale, and troubleshoot the site, how to add database, authentication, and authorization functionality, and how to decide if your application should run in a Windows Azure Cloud Service instead of a Windows Azure Web Site.

How to manage a web site

When you're done with the site, you can delete it, and at times you might want to take it offline temporarily or change site settings. You can do some of these functions right from Server Explorer in Visual Studio.
Windows Azure Web Sites in Server Explorer
Web Site Configuration in Visual Studio
For more information, see Web Sites: Management Support within the Visual Studio Server Explorer in Announcing the release of Windows Azure SDK 2.0 for .NET on ScottGu's blog.
To delete your web site, you can use the Windows Azure Management Portal. The following screen shot shows Stop, Restart, and Delete buttons in the Dashboard tab of the management portal.
Management Portal Dashboard Tab
You can change site settings on the Configure tab. For more information, see How to Manage Web Sites.

How to scale a web site

When your site is public and it starts to get more traffic, response times might slow down. To remedy that, you can easily add server resources in the Scale tab of the management portal.
Management Portal Scale Tab
For more information, see How to Scale a Web Site. (Adding server resources to scale a web site is not free.)

How to troubleshoot a web site

If the site stops working correctly, you might want to look at trace or log output for help with troubleshooting. Visual Studio provides built-in tooling to make it easy to view Windows Azure logs as they are generated in real time.
Logs in Visual Studio
For more information, see Web Sites: Streaming Diagnostic Logs in Announcing the release of Windows Azure SDK 2.0 for .NET on ScottGu's blog. For information about web site monitoring functions that are available from the management portal, see How to Monitor Web Sites.

How to add database and authorization functionality

Most production web sites use a database and restrict some site functions to certain authorized users. For a tutorial that shows how to get started with database access, authentication, and authorization, see Deploy a Secure ASP.NET MVC app with Membership, OAuth, and SQL Database to a Windows Azure Web Site.

How to decide if your application should run in a Cloud Service

In some scenarios you might want to run your application in a Windows Azure Cloud Service instead of a Windows Azure Web Site. For more information, see Windows Azure Execution Models. For a tutorial series that shows how to create a multi-tier ASP.NET web application and deploy it to a Cloud Service, see .NET Multi-Tier Application Using Storage Tables, Queues, and Blobs.

No comments :

Post a Comment

PHP/MySQL Insert & Delete using jQuery/Ajax

No comments
Demo Download
 

Demo Download

No comments :

Post a Comment

Stopping CSRF Attacks in PHP

No comments

Form


Processing Page


No comments :

Post a Comment

Use Selectors in jQuery

No comments
The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.
  • $("li:not(.myclass)"): Selects all elements matched by
  • that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within elements.
  • $("ul li:first"): This selector gets only the first
  • element of the
      .
  • $("#container p"): Selects all elements matched by that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by
      that are children of an element matched by
  • $("strong + em"): Selects all elements matched by that immediately follow a sibling element matched by .
  • $("p ~ ul"): Selects all elements matched by
      that follow a sibling element matched by .
  • $("code, em, strong"): Selects all elements matched by or or .
  • $("p strong, .myclass"): Selects all elements matched by that are descendants of an element matched by as well as all elements that have a class of myclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by that have no children.
  • $("div[p]"): Selects all elements matched by
    that contain an element matched by .
  • $("p[.myclass]"): Selects all elements matched by that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by that have a class value ending with bar
  • $("a[@href*=domain.com]"): Selects all elements matched by that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by
  • that have an even index value.
  • $("tr:odd"): Selects all elements matched by that have an odd index value.
  • $("li:first"): Selects the first
  • element.
  • $("li:last"): Selects the last
  • element.
  • $("li:visible"): Selects all elements matched by
  • that are visible.
  • $("li:hidden"): Selects all elements matched by
  • that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third
  • element
  • $("li:eq(4)"): Selects the fifth
  • element
  • $("li:lt(2)"): Selects all elements matched by
  • element before the third one; in other words, the first two
  • elements.
  • $("p:lt(3)"): selects all elements matched by elements before the fourth one; in other words the first three elements.
  • $("li:gt(1)"): Selects all elements matched by
  • after the second one.
  • $("p:gt(2)"): Selects all elements matched by after the third one.
  • $("div/p"): Selects all elements matched by that are children of an element matched by
    .
  • $("div//code"): Selects all elements matched by that are descendants of an element matched by
    .
  • $("//p//a"): Selects all elements matched by that are descendants of an element matched by
  • $("li:first-child"): Selects all elements matched by
  • that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by
  • that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by
  • that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for
  • element then $("p:first") would also work for element.

  • No comments :

    Post a Comment

    FirstOrDefault Value by Linq

    No comments
    model = from b in db.books.Take(6).ToList()
           where b.writerId==id
           select b;

    var wtrName = model.FirstOrDefault().writer.WriterName;
    ViewBag.title = "Book List of Writer : " + wtrName;

    No comments :

    Post a Comment

    Display All Images from Directory

    No comments
    Model
    public class ImagesModel
        {
            public ImagesModel()
            {
                Images = new List();
            }

            public List Images { get; set; }
        }


    Controller
    Method Index

    public ActionResult Index()
            {
                var images = new ImagesModel();
                //Read out files from the files directory
                var files = Directory.GetFiles(Server.MapPath("~/Content/img"));
                //Add them to the model
                foreach (var file in files)
                    images.Images.Add(Path.GetFileName(file));

                return View(images);
            }

    View
    Index Display part

    
    @foreach (var src in Model.Images)
    {
        

    }

    No comments :

    Post a Comment

    Combo Box, Drop Down List in MVC using Entity Framework

    No comments
    Combo Box, Drop Down List in MVC 4 ASP.NET using Entity Framework>
    Models Class
    writer.cs
    public class Writer
    {
    public int WriterId { get; set; }
    public string WriterName { get; set; }
    }


    book.cs
    [Bind(Exclude="bookId")]
    public class book
    {
    public int bookId { get; set; }
    [Required]
    public int writerId { get; set; }
    [Required]
    public string title { get; set; }
    public decimal price { get; set; }
    public string imagepath { get; set; }
    }

    Controller 

    bookController.cs
    public ActionResult Create()
    {
    ViewBag.WriterId = new SelectList(db.writers, "WriterId", "WriterName");
    return View();
    }


    View
    Create.cshtml
    @Html.DropDownList("WriterId",string.Empty)

    No comments :

    Post a Comment

    Using Entity Framework

    No comments
    Model

        [Bind(Exclude="GenreId")]
        public class Genre
        {
            [ScaffoldColumn(false)]
            public int GenreId { get; set; }
            public string GenreName { get; set; }
            public string Description { get; set; }
            public Boolean Status { get; set; }
                 
        }



    Entity Class

        public class MVCBookStoreEntities:DbContext
        {
            public MVCBookStoreEntities()
                : base("name=ApplicationServices")
            { }
            public DbSet genres { get; set; }
        }

    Global.asax

    on Application_Start add this
           
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges());


    Controller


    MVCBookStoreEntities db = new MVCBookStoreEntities();

            public ActionResult Index()
            {
                List gen =new List();
                gen=db.genres.ToList();
                var model=from g in gen
                          orderby g.GenreId descending
                          where g.Status==true
                          select g;
                return View(model);
            }

    No comments :

    Post a Comment

    MVC Complete Add/Edit/Delete/Details Controller with Entity FrameWork

    No comments
    public class genreController : Controller
        {
            //
            // GET: /genre/
            MVCBookStoreEntities db = new MVCBookStoreEntities();

            public ActionResult Index()
            {
                //var model = db.genres.ToList();
                //return View(model);          

                List gen =new List();
                gen=db.genres.ToList();
                var model=from g in gen
                          orderby g.GenreId descending
                          where g.Status==true
                          select g;
                return View(model);
            }


            //
            // GET: /genre/Details/5

            public ActionResult Details(int id)
            {
                var model = db.genres.Find(id);
                return View(model);
            }

            //
            // GET: /genre/Create

            public ActionResult Create()
            {
                return View();
            }

            //
            // POST: /genre/Create

            [HttpPost]
            public ActionResult Create(Genre addgen)
            // public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    //return RedirectToAction("Index");
                    db.Entry(addgen).State = EntityState.Added;
                    //db.genres.Add(addgen);
                    db.SaveChanges();
                    return RedirectToAction("Index");


                }
                catch
                {
                    return View();
                }
            }

            //
            // GET: /genre/Edit/5

            public ActionResult Edit(int id)
            {
                var model=db.genres.Find(id);
                return View(model);
            }

            //
            // POST: /genre/Edit/5

            [HttpPost]
            public ActionResult Edit(int id, Genre editgen)
            //public ActionResult Edit(int id, FormCollection collection)
            {
                    try
                    {
                        if (ModelState.IsValid)
                        {
                            // TODO: Add update logic here
                            editgen.GenreId = id;
                            db.Entry(editgen).State = EntityState.Modified;
                            db.SaveChanges();
                            return RedirectToAction("Index");
                        }
                        else {
                            return RedirectToAction("Index");
                        }
                    }
                    catch
                    {
                        return View();
                    }
               
            }

            //
            // GET: /genre/Delete/5

            public ActionResult Delete(int id)
            {
                var model = db.genres.Find(id);
                return View(model);
            }

            //
            // POST: /genre/Delete/5

            [HttpPost]
            public ActionResult Delete(int id, Genre deletegen)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        // TODO: Add update logic here
                        deletegen.GenreId = id;
                        db.Entry(deletegen).State = EntityState.Deleted;
                        db.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
                }
                catch
                {
                    return View();
                }
            }
        }

    No comments :

    Post a Comment

    Installation of EntityFramework 6.0.0-beta1

    No comments
    Microsoft Visual Studio 2012

    Tools
    Library Package Manager
    Package Manager Console

    Then
    PM> Install-Package EntityFramework -Pre  

    required Internet Connection............

    No comments :

    Post a Comment

    Scaffold (programming)

    No comments
    Scaffolding is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used. The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a "scaffold" on which to build a more powerful application.

    No comments :

    Post a Comment

    Introduction to LINQ

    No comments
    Language-Integrated Query (LINQ) is an innovation introduced in Visual Studio 2008 and .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data.
    Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. LINQ makes a query a first-class language construct in C# and Visual Basic. You write queries against strongly typed collections of objects by using language keywords and familiar operators. The following illustration shows a partially-completed LINQ query against a SQL Server database in C# with full type checking and IntelliSense support.
    LINQ query with Intellisense In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support for the ADO.NET Entity Framework is also planned, and LINQ providers are being written by third parties for many Web services and other database implementations.
    You can use LINQ queries in new projects, or alongside non-LINQ queries in existing projects. The only requirement is that the project target .NET Framework 3.5 or later.

    No comments :

    Post a Comment

    Introduction to Generic Classes and Inheritance

    No comments
    Consider the following geometric figures:
    Square Rectangle Trapezoid Parallelogram
    Square Rectangle Trapezoid Parallelogram
    Notice that these are geometric figures with each having four sides. From what we know so far, we can create a base class to prepare it for inheritance. If the class is very general, we can make it a generic one. We can set a data type as an unknown type, anticipating that the dimensions of the figure can be considered as integer or double-precision types. Here is an example:
    using System;
    
    public class Quadrilateral
    {
            protected T _base;
            protected T _height;
            protected string _name;
    
            public virtual T Base
            {
                get { return _base; }
                set { _base = value; }
            }
    
            public virtual T Height
            {
                get { return _height; }
                set { _height = value; }
            }
    
            public virtual string Name
            {
                get { return _name; }
                set { _name = value; }
            }
    
            public Quadrilateral(string name = "Quadrilateral")
            {
                _name = name;
            }
    
            public Quadrilateral(T bs, T height)
            {
                _name = "Quadrilateral";
                _base = bs;
                _height = height;
            }
    
            public Quadrilateral(string name, T bs, T height)
            {
                _name = name;
                _base = bs;
                _height = height;
            }
    
    
            public virtual string Describe()
            {
                return "A quadrilateral is a geometric figure with four sides";
            }
    
            public virtual void ShowCharacteristics()
            {
                Console.WriteLine("Geometric Figure: {0}", Name);
                Console.WriteLine("Description:      {0}", Describe());
                Console.WriteLine("Base:             {0}", Base);
                Console.WriteLine("Height:           {0}", Height);
            }
    }
    
    public class Exercise
    {
        static int Main()
        {
            // Trapezoid with equal sides
            var Kite = new Quadrilateral("Beach Kite", 18.64, 18.64);
            Kite.ShowCharacteristics();
            Console.WriteLine();
    
            // Rectangle, in meters
            var BasketballStadium = new Quadrilateral();
            BasketballStadium.Name = "Basketball Stadium";
            BasketballStadium.Base = 15;
            BasketballStadium.Height = 28;
            BasketballStadium.ShowCharacteristics();
            Console.WriteLine();
    
            return 0;
        }
    }
    This would produce:
    Geometric Figure: Beach Kite
    Description:      A quadrilateral is a geometric figure with four sides
    Base:             18.64
    Height:           18.64
    
    Geometric Figure: Basketball Stadium
    Description:      A quadrilateral is a geometric figure with four sides
    Base:             15
    Height:           28
    
    Press any key to continue . . .
    If you have a generic class that can serve as a foundation for another class, you can derive a class from the generic one. To do this, use the formula we apply when deriving a class but follow the name of each class with <>. Inside of the <> operator, enter the same identifier to indicate that the class is a generic type that is based on another generic class. Here is an example:
    public class Square : Quadrilateral
    {
    }
    In the body of the new class, you can use the parameter type as you see fit. For example, you can declare some member variables of that type. You can create methods that return the parameter type or you can pass arguments of the parameter type. When implementing the methods of the new class, use the member variables of the parameter and the argument(s) based on the parameter type as you see fit. You can then declare a variable of the class and use it as we done so far for other generic classes. Here is an example:
    using System;
    
    public class Quadrilateral
    {
            protected T _base;
            protected T _height;
            protected string _name;
    
            public virtual T Base
            {
                get { return _base; }
                set { _base = value; }
            }
    
            public virtual T Height
            {
                get { return _height; }
                set { _height = value; }
            }
    
            public virtual string Name
            {
                get { return _name; }
                set { _name = value; }
            }
    
            public Quadrilateral(string name = "Quadrilateral")
            {
                _name = name;
            }
    
            public Quadrilateral(T bs, T height)
            {
                _name = "Quadrilateral";
                _base = bs;
                _height = height;
            }
    
            public Quadrilateral(string name, T bs, T height)
            {
                _name = name;
                _base = bs;
                _height = height;
            }
    
    
            public virtual string Describe()
            {
                return "A quadrilateral is a geometric figure with four sides";
            }
    
            public virtual void ShowCharacteristics()
            {
                Console.WriteLine("Geometric Figure: {0}", Name);
                Console.WriteLine("Description:      {0}", Describe());
                Console.WriteLine("Base:             {0}", Base);
                Console.WriteLine("Height:           {0}", Height);
            }
    }
    
    public class Square : Quadrilateral
    {
            public Square()
            {
                _name = "Square";
            }
            public Square(string name)
            {
                _name = "Square";
            }
            public Square(T side)
            {
                _name = "Square";
                _base = side;
                _height = side;
            }
            public Square(string name, T side)
            {
                _name = name;
                _base = side;
                _height = side;
            }
            public override string Describe()
            {
                return "A square is a quadrilateral with four equal sides";
            }
            public override void ShowCharacteristics()
            {
                Console.WriteLine("Geometric Figure: {0}", Name);
                Console.WriteLine("Description:      {0}", Describe());
                Console.WriteLine("                  {0}", Describe());
                Console.WriteLine("Side:             {0}", Base);
            }
    }
    
    public class Exercise
    {
        static int Main()
        {
            // Rectangle, in meters
            var plate = new Square();
    
            plate.Name   = "Plate";
     plate.Base   = 15;
            plate.Height = 28;
     plate.ShowCharacteristics();
    
            Console.WriteLine();
            return 0;
        }
    }
    This would produce:
    Geometric Figure: Plate
    Description:      A quadrilateral is a geometric figure with four sides
                      A square is a quadrilateral with four equal sides
    Side:             15
    
    Press any key to continue . . .

    No comments :

    Post a Comment

    5 Different Ways to Declare Functions in jQuery

    No comments

    From jQuery4u

    Introduction

    Choosing which way to declare a JavaScript function can be confusing for beginners as there are several different ways to declare functions using JavaScript/jQuery. I’ll try to explain the benefits of each one and how and why you might use them when writing your awesome jQuery code.

    1. The basic JavaScript function

    This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called multiply(x,y) which simply takes in two parameters x and y, does a simple x times y and returns the value. Here are a few ways you might go about doing exactly this.

    function multiply(x,y) {
         return (x * y);
    }
    console.log(multiply(2,2));
    //output: 4
    If you wanted a quick function to test something then maybe that’s the only occasion you would use this. It’s not good coding and doesn’t promote code reuse.

    2. JavaScript functions for get/set

    If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.

    var multiply = function(x,y) {
         return (x * y);
    }
    console.log(multiply(2,2));
    //output: 4

    //The same function but with a self execution to set the value of the variable:
    var multiply = function(x,y) {
         return (x * y);
    }(2,2);
    console.log(multiply);
    //output: 4

    3. Create your own jQuery function

    This is an awesome way to declare functions that can be used just like your regular jQuery functions, on your DOM elements! Rememeber jQuery.fn is just an alias for jQuery.prototype (which just saves us time when coding such jQuery.fn.init.prototype = jQuery.fn = $.fn as such).

    jQuery.fn.extend({
        zigzag: function () {
            var text = $(this).text();
            var zigzagText = '';
            var toggle = true; //lower/uppper toggle
                $.each(text, function(i, nome) {
                    zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                    toggle = (toggle) ? false : true;
                });
        return zigzagText;
        }
    });

    console.log($('#tagline').zigzag());
    //output: #1 jQuErY BlOg fOr yOuR DaIlY NeWs, PlUgInS, tUtS/TiPs & cOdE SnIpPeTs.

    //chained example
    console.log($('#tagline').zigzag().toLowerCase());
    //output: #1 jquery blog for your daily news, plugins, tuts/tips & code snippets.
    Don’t forget to return the element so that you can chain jQuery functions together.

    4. Extend Existing jQuery Functions

    (or which either extend existing jQuery functions with extra functionality or creating your own functions that can be called using the jQuery namespace (usually, we use the $ sign to represent the jQuery namespace). In this example the $.fn.each function has been modified with custom behaviour.

    (function($){

    // maintain a to the existing function
    var oldEachFn = $.fn.each;

    $.fn.each = function() {

        // original behavior - use function.apply to preserve context
        var ret = oldEachFn.apply(this, arguments);
       
        // add custom behaviour
        try {
            // change background colour
            $(this).css({'background-color':'orange'});
           
            // add a message
            var msg = 'Danger high voltage!';
            $(this).prepend(msg);
        }
        catch(e)
        {
            console.log(e);
        }
       
        // preserve return value (probably the jQuery object...)
        return ret;
    }

    // run the $.fn.each function as normal
    $('p').each(function(i,v)
    {
        console.log(i,v);
    });
    //output: all paragrahs on page now appear with orange background and high voltage!

    })(jQuery);

    5. Functions in custom namespaces

    If your writing functions in a custom namespace you must declare them in this way. Extra functions can be added to the namespace you just need to add a comma after each one (except the last one!). If your unsure about namespacing see jQuery Function Namespacing in Plain English

    JQUERY4U = {
        multiply: function(x,y) {
            return (x * y);
        }
    }
    //function call
    JQUERY4U.multiply(2,2);

    Conclusion

    Knowing when and how to declare different types of JavaScript/jQuery functions is definitely something any good js developer should know inside out.

    No comments :

    Post a Comment

    An Introduction to Stored Procedures in MySQL 5

    No comments

    Introduction

    “ A stored routine is a set of SQL statements that can be stored in the server.”
    A stored procedure is a method to encapsulate repetitive tasks. They allow for variable declarations, flow control and other useful programming techniques.
    The “academic” position on this is quite clear and supports the extensive use of stored procedures. On the other hand, when you consider the opinions of those who work with them day in, day out, you’ll notice that reactions vary from complete, unwavering support to utter hate. Keep these in mind.

    Pros

    • Share logic with other applications. Stored procedures encapsulate functionality; this ensures that data access and manipulation are coherent between different applications.
    • Isolate users from data tables. This gives you the ability to grant access to the stored procedures that manipulate the data but not directly to the tables.
    • Provide a security mechanism. Considering the prior item, if you can only access the data using the stored procedures defined, no one else can execute a DELETE SQL statement and erase your data.
    • To improve performance because it reduces network traffic. With a stored procedure, multiple calls can be melded into one.

    Cons

    • Increased load on the database server — most of the work is done on the server side, and less on the client side.
    • There’s a decent learning curve. You’ll need to learn the syntax of MySQL statements in order to write stored procedures.
    • You are repeating the logic of your application in two different places: your server code and the stored procedures code, making things a bit more difficult to maintain.
    • Migrating to a different database management system (DB2, SQL Server, etc) may potentially be more difficult.
    The tool that I am working with in this tutorial, MySQL Query Browser, is pretty standard for database interactions. The MySQL command line tool is another excellent choice. I make note of this because the popular phpMyAdmin doesn’t support stored procedure execution.
    Additionally, I’ll be using very rudimentary table structures, strictly to ease the explanation. I’m showing off stored procedures, and they’re complex enough without worrying about big tables.

    Step 1 – Picking a Delimiter

    The delimiter is the character or string of characters that you’ll use to tell the mySQL client that you’ve finished typing in an SQL statement. For ages, the delimiter has always been a semicolon. That, however, causes problems, because, in a stored procedure, one can have many statements, and each must end with a semicolon. In this tutorial I will use “//”

    Step 2 – How to Work with a Stored Procedure

    Creating a Stored Procedure

    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `p2` ()  
    4. LANGUAGE SQL  
    5. DETERMINISTIC  
    6. SQL SECURITY DEFINER  
    7. COMMENT 'A procedure'  
    8. BEGIN  
    9.     SELECT 'Hello World !';  
    10. END//  
    The first part of the statement creates the procedure. The next clauses defines the optional characteristics of the procedure. Then you have the name and finally the body or routine code.
    Stored procedure names are case insensitive, and you cannot create procedures with the same name. Inside a procedure body, you can’t put database-manipulation statements.
    The four characteristics of a procedure are:
    • Language : For portability purposes; the default value is SQL.
    • Deterministic : If the procedure always returns the same results, given the same input. This is for replication and logging purposes. The default value is NOT DETERMINISTIC.
    • SQL Security : At call time, check privileges of the user. INVOKER is the user who calls the procedure. DEFINER is the creator of the procedure. The default value is DEFINER.
    • Comment : For documentation purposes; the default value is ""

    Calling a Stored Procedure

    To call a procedure, you only need to enter the word CALL, followed by the name of the procedure, and then the parentheses, including all the parameters between them (variables or values). Parentheses are compulsory.
    1. CALL stored_procedure_name (param1, param2, ....)  
    2.   
    3. CALL procedure1(10 , 'string parameter' , @parameter_var);  

    Modify a Stored Procedure

    MySQL provides an ALTER PROCEDURE statement to modify a routine, but only allows for the ability to change certain characteristics. If you need to alter the body or the parameters, you must drop and recreate the procedure.

    Delete a Stored Procedure

    1. DROP PROCEDURE IF EXISTS p2;  
    This is a simple command. The IF EXISTS clause prevents an error in case the procedure does not exist.

    Step 3 – Parameters

    Let’s examine how you can define parameters within a stored procedure.
    • CREATE PROCEDURE proc1 () : Parameter list is empty
    • CREATE PROCEDURE proc1 (IN varname DATA-TYPE) : One input parameter. The word IN is optional because parameters are IN (input) by default.
    • CREATE PROCEDURE proc1 (OUT varname DATA-TYPE) : One output parameter.
    • CREATE PROCEDURE proc1 (INOUT varname DATA-TYPE) : One parameter which is both input and output.
    Of course, you can define multiple parameters defined with different types.

    IN example

    1.    DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_IN` (IN var1 INT)  
    4. BEGIN  
    5.     SELECT var1 + 2 AS result;  
    6. END//  

    OUT example

    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_OUT` (OUT var1 VARCHAR(100))  
    4. BEGIN  
    5.     SET var1 = 'This is a test';  
    6. END //  

    INOUT example

    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_INOUT` (OUT var1 INT)  
    4. BEGIN  
    5.     SET var1 = var1 * 2;  
    6. END //  

    Step 4 – Variables

    The following step will teach you how to define variables, and store values inside a procedure. You must declare them explicitly at the start of the BEGIN/END block, along with their data types. Once you’ve declared a variable, you can use it anywhere that you could use a session variable, or literal, or column name.
    Declare a variable using the following syntax:
    1. DECLARE varname DATA-TYPE DEFAULT defaultvalue;   
    Let’s declare a few variables:
    1. DECLARE a, b INT DEFAULT 5;  
    2.   
    3. DECLARE str VARCHAR(50);  
    4.   
    5. DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;  
    6.   
    7. DECLARE v1, v2, v3 TINYINT;  

    Working with variables

    Once the variables have been declared, you can assign them values using the SET or SELECT command:
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `var_proc` (IN paramstr VARCHAR(20))  
    4. BEGIN  
    5.     DECLARE a, b INT DEFAULT 5;  
    6.     DECLARE str VARCHAR(50);  
    7.     DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;  
    8.     DECLARE v1, v2, v3 TINYINT;      
    9.   
    10.     INSERT INTO table1 VALUES (a);  
    11.     SET str = 'I am a string';  
    12.     SELECT CONCAT(str,paramstr), today FROM table2 WHERE b >=5;   
    13. END //  

    Step 5 – Flow Control Structures

    MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE and REPEAT constructs for flow control within stored programs. We’re going to review how to use IF, CASE and WHILE specifically, since they happen to be the most commonly used statements in routines.

    IF statement

    With the IF statement, we can handle tasks which involves conditions:
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_IF` (IN param1 INT)  
    4. BEGIN  
    5.     DECLARE variable1 INT;  
    6.     SET variable1 = param1 + 1;  
    7.       
    8.     IF variable1 = 0 THEN  
    9.         SELECT variable1;  
    10.     END IF;  
    11.   
    12.     IF param1 = 0 THEN  
    13.         SELECT 'Parameter value = 0';  
    14.     ELSE  
    15.         SELECT 'Parameter value <> 0';  
    16.     END IF;  
    17. END //  

    CASE statement

    The CASE statement is another way to check conditions and take the appropriate path. It’s an excellent way to replace multiple IF statements. The statement can be written in two different ways, providing great flexibility to handle multiple conditions.
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_CASE` (IN param1 INT)  
    4. BEGIN  
    5.     DECLARE variable1 INT;  
    6.     SET variable1 = param1 + 1;  
    7.       
    8.     CASE variable1  
    9.         WHEN 0 THEN  
    10.             INSERT INTO table1 VALUES (param1);  
    11.         WHEN 1 THEN  
    12.             INSERT INTO table1 VALUES (variable1);   
    13.         ELSE  
    14.             INSERT INTO table1 VALUES (99);  
    15.     END CASE;  
    16.   
    17. END //  
    or:
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_CASE` (IN param1 INT)  
    4. BEGIN  
    5.     DECLARE variable1 INT;  
    6.     SET variable1 = param1 + 1;  
    7.       
    8.     CASE   
    9.         WHEN variable1 = 0 THEN  
    10.             INSERT INTO table1 VALUES (param1);  
    11.         WHEN variable1 = 1 THEN  
    12.             INSERT INTO table1 VALUES (variable1);   
    13.         ELSE  
    14.             INSERT INTO table1 VALUES (99);  
    15.     END CASE;  
    16.   
    17. END //  

    WHILE statement

    There are technically three standard loops: WHILE loops, LOOP loops, and REPEAT loops. You also have the option of creating a loop using the “Darth Vader” of programming techniques: the GOTO statement. Check out this example of a loop in action:
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_WHILE` (IN param1 INT)  
    4. BEGIN  
    5.     DECLARE variable1, variable2 INT;  
    6.     SET variable1 = 0;  
    7.       
    8.     WHILE variable1 < param1 DO  
    9.         INSERT INTO table1 VALUES (param1);  
    10.         SELECT COUNT(*) INTO variable2 FROM table1;  
    11.         SET variable1 = variable1 + 1;  
    12.     END WHILE;  
    13. END //  

    Step 6 - Cursors

    Cursor is used to iterate through a set of rows returned by a query and process each row.
    MySQL supports cursor in stored procedures. Here's a summary of the essential syntax to create and use a cursor.
    1. DECLARE cursor-name CURSOR FOR SELECT ...;       /*Declare and populate the cursor with a SELECT statement */  
    2. DECLARE  CONTINUE HANDLER FOR NOT FOUND          /*Specify what to do when no more records found*/  
    3. OPEN cursor-name;                                /*Open cursor for use*/  
    4. FETCH cursor-name INTO variable [, variable];    /*Assign variables with the current column values*/  
    5. CLOSE cursor-name;                               /*Close cursor after use*/  
    In this example, we'll perform some simple operations using a cursor:
    1. DELIMITER //  
    2.   
    3. CREATE PROCEDURE `proc_CURSOR` (OUT param1 INT)  
    4. BEGIN  
    5.     DECLARE a, b, c INT;  
    6.     DECLARE cur1 CURSOR FOR SELECT col1 FROM table1;  
    7.     DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;  
    8.     OPEN cur1;  
    9.   
    10.     SET b = 0;  
    11.     SET c = 0;  
    12.      
    13.     WHILE b = 0 DO  
    14.         FETCH cur1 INTO a;  
    15.         IF b = 0 THEN  
    16.             SET c = c + a;  
    17.     END IF;    
    18.     END WHILE;  
    19.   
    20.     CLOSE cur1;  
    21.     SET param1 = c;  
    22.   
    23. END //  
    Cursor has three important properties that you need to be familiar with in order to avoid unexpected results:
    • Asensitive : Once open, the cursor will not reflect changes in its source tables. In fact, MySQL does not guarantee the cursor will be updated, so you can't rely on it.
    • Read Only : Cursors are not updatable.
    • Not Scrollable : Cursors can be traversed only in one direction, forward, and you can't skip records from fetching.

    Conclusion

    In this lesson, we covered the fundamentals of stored procedures and some specific properties pertaining to them. Of course, you should continue your studies in areas like security, SQL statements, and performance before you can master MySQL routines.
    You have to evaluate the advantages that stored procedures can potentially bring to your applications, and then make a reasonable implementation that fits your requirements. I generally use procedures; their benefits in terms of security, code maintenance and software design make them worthy of use, in my opinion. Additionally, remember that procedures in MySQL are still a work in progress. You should fully expect improvements, in terms of functionality and performance in the future. Please don't hesitate to comment and share your ideas and opinions.

    No comments :

    Post a Comment