Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE.eu :: How to Create Strong Password for AngularJS Pages?

clock September 18, 2020 08:28 by author Peter

In this post, let me explain you how to create strong password for AngularJS. For choosing a password we need combination of special characters, Capital letter , small letters, digits etc to make it strong. Write the following code:

    <!DOCTYPE html> 
    <html> 
    <head> 
        <title>Strong Password for Angular UI Pages</title>            
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>   
        <script> 
            var app = angular.module("myApp", []); 
            app.controller("myCtrl", function ($scope) {        
                var strongRegularExp = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[[email protected]#\$%\^&\*])(?=.{8,})");        
                var mediumRegularExp = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");        
                $scope.checkpwdStrength = { 
                    "width": "150px", 
                    "height": "25px", 
                    "float": "right" 
                };        
                $scope.validationInputPwdText = function (value) { 
                    if (strongRegularExp.test(value)) { 
                        $scope.checkpwdStrength["background-color"] = "green"; 
                        $scope.userPasswordstrength = 'You have a Very Strong Password now'; 
                    } else if (mediumRegularExp.test(value)) { 
                        $scope.checkpwdStrength["background-color"] = "orange"; 
                        $scope.userPasswordstrength = 'Strong password, Please give a very strong password';  
                    } else { 
                        $scope.checkpwdStrength["background-color"] = "red"; 
                        $scope.userPasswordstrength = 'Weak Password , Please give a strong password'; 
                    }                  
};        
           }); 
        </script> 
    </head> 
    <body ng-app="myApp"> 
        <div ng-controller="myCtrl" style="border:5px solid gray; width:800px;"> 
            <div> 
                <h3>Strong Password for Angular UI Pages </h3> 
            </div> 
            <div style="padding-left:25px;">                  
<div ng-style="checkpwdStrength"></div> 
                <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" /> 
                <b> {{userPasswordstrength}}</b> 
            </div> 
            <br /> 
            <br /> 
            <br /> 
        </div> 
    </body> 
    </html> 

HostForLIFE.eu AngularJS Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European Ajax Hosting UK - HostForLIFE.eu :: How to Make Custom Alert Message with Ajax?

clock September 4, 2020 07:56 by author Peter

In this article, we are going to learn how to make custom Alert Message with Ajax. Some time we needed to make clone of windows alert message, however that alert message isn't permitting to change the header text. Here using Ajax model popup extender i'll show you how to make custom message box:
Add the user control file and ajaxtoolkit reference in your project.

Write the following code in ascx file.
<style type="text/css">
.MessageBoxPopUp
{
background-color:White;
border:solid 2px #99B4D1;
}

.MessageBoxButton
{
background-color: #A0A0A0;
border: solid 2px #B4B4B4;
color: Black;
font-weight:bold;
font-family:Verdana;
font-size:9pt;
cursor:pointer;
height: 20px;
width:70px;
display:none;
}
.MessageBoxHeader
{
height:17px;
font-size:10pt;
color:White;
font-weight:bold;
font-family:Verdana;
text-align:Left;
vertical-align:middle;
padding:3px 3px 3px 3px;
background-color:#3399FF;
border-bottom:2px solid #B4B4B4;
}
.MessageBoxData
{
height:20px;
font-size:8pt;
font-family:Verdana;
color:#3A4349;
text-align:Left;
vertical-align:top;
}
</style>
<script type="text/javascript">
function closeModelPopup(btn) {
// var mpe = document.getElementById("<%= mpeMessageBox.ClientID %>");
$find('mpeFirmMessageBox').hide();
}
</script>

<cc1:ModalPopupExtender ID="mpeMessageBox" runat="server" DynamicServicePath="" Enabled="True"
TargetControlID="btnTemp" PopupControlID="pnlMessageBox" BackgroundCssClass="modal"
PopupDragHandleControlID="pnlMessageBox" CancelControlID="btnCancel" BehaviorID="mpeFirmMessageBox">
</cc1:ModalPopupExtender>

<asp:Panel ID="pnlMessageBox" runat="server" Style="display: none; width: 300px;
height: 140px;" class="MessageBoxPopUp">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr class="MessageBoxHeader" style="height: 17px;">

<td colspan="2">
    <asp:Label ID="lblHeader" runat="server"></asp:Label>
</td>

<td align="right" style="padding: 2px 2px 0px 0px;">
    <%--<asp:UpdatePanel ID="upnCloseMessageBox" runat="server">
        <ContentTemplate>--%>
            <asp:ImageButton ID="imgBtnClose" runat="server" ImageUrl="~/Image/close_icon.png"
                 OnClientClick="closeModelPopup(this)" />
        <%--</ContentTemplate>
    </asp:UpdatePanel>--%>
</td>
</tr>

<tr>
<td colspan="2" style="height: 5px;">
</td>
</tr>
<tr style="height: 88px;">

<td style="vertical-align: top; padding-left: 5px;">
    <asp:Image ID="imgInfo" runat="server" ImageUrl="~/Image/information-balloon.png" Width="40px" />
</td>

<td class="MessageBoxData" colspan="2" style=" padding: 10px 5px 5px 5px;">
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>

</tr>
<tr style="vertical-align: bottom; height: 20px; padding: 0px 5px 5px 0px;">
<td style="width: 40px;">
</td>
<td align="right" style="width: 180px">
    <asp:Button ID="btnOk" runat="server" CssClass="MessageBoxButton" />
</td>

<td align="right">
    <asp:Button ID="btnCancel" runat="server" CssClass="MessageBoxButton" />
</td>
</tr>
</table>
</asp:Panel>

Now, add the following code in .cs file
public delegate void delegate_OkClick();
public event delegate_OkClick OnOkClick;
public string Header
{
set { lblHeader.Text = value; }
//set { lblHeader.InnerHtml = value; }
}

public string Message
{
set { lblMessage.Text = value; }
}

public Button CancelButton
{
get { return btnCancel; }
}

public Button OkButton
{
get { return btnOk; }
}

public AjaxControlToolkit.ModalPopupExtender MessageBox
{
get { return mpeMessageBox; }
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnOk_OnClick(object sender, EventArgs e)
{
//raise the event if not null
if (OnOkClick != null)
OnOkClick();
}
public void displayMessage(string message)
{
displayMessage(message, null);
}
public void displayMessage(string message, int? type)

{

lblHeader.Text = "Alert Message";
//lblHeader.InnerHtml = title;
lblMessage.Text = message;
btnCancel.Attributes["style"] = "display:block";
btnCancel.Text = "Ok";
mpeMessageBox.Show();
}


Your message box is ready, now you need to call from the aspx page where ever you need to show the message.
You need to add below line of code in
<%@ Register Src="~/Control/Alert.ascx" TagName="MessageBox" TagPrefix="mb" %>
<asp:ScriptManager runat="server" ID="s"></asp:ScriptManager>
<mb:MessageBox ID="ucMessageBox" runat="server"></mb:MessageBox>

And from the code behind cal the display message write the following code:
protected void btnClick_OnClik(object sender, EventArgs e)
{
ucMessageBox.displayMessage("Alert from Code");
}

HostForLIFE.eu AJAX Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European WCF Hosting - HostForLIFE.eu :: Why Should We Use WCF?

clock August 28, 2020 07:58 by author Peter

What is WCF?
WCF stands for ‘Windows Communication Foundation’. It is a Microsoft platform for building distributed and interoperable applications.

What is a distributed application?
A distributed application is an application where part of it runs on two or more computer nodes. Distributed applications are called ‘Connected systems’ also.

Now, let us see the above diagram where a Windows application is stored on one computer and the web service that it is consuming is running on another computer (which can be situated anywhere in the world). Well, this is a connected system.

Why build distributed applications?
    Interdependency
    An enterprise application may need to use the service provide by other enterprise, For example, an ecommerce application using Paytm for payments.

    For better scalability
    Scalability of an application implies the number of visitors an application can handle without degrading the performance. We can break down the application into different layers that run on different computers. Each of these computers will have its own memory and processor, which helps with improving the scalability of the application.

What is an interoperable application?
An application that can communicate with any other application that is built on any platform is called an interoperable application. Web Services can communicate with any application built on any platform, whereas .NET remoting service can be consumed only by another .NET application.

Why should we use WCF?

Without WCF,

Consider a situation where we have 2 clients and we need to implement a service for them.

The first client is using a Java application to interact with our services. This client wants a message to be in XML format and the protocol to be in HTTP. Without WCF, to satisfy the first client requirement, we will have to create an ASMX web service.


The second Client is using .NET and for better performance, this client wants a message format in binary format and protocol to be in TCP. Without WCF, to satisfy the second client requirement, we will create a .NET Remoting service.

 

.NET remoting and ASMX are two different technologies, and have completely different programming models. Therefore, developers have to learn two different technologies, which is not only time and cost consuming but needs two people with expertise.

So to unite and bring all these communication technologies under one roof, Microsoft has come up with a single programming model that is called WCF. WCF is going to unify everything, such as .NET Remoting, IPC, MSMQ queue, TCP, Peer networking, and all other communication technologies we have.

With WCF
With WCF, for both the clients, we will implement only one service and to satisfy the requirement of different clients, we will configure different end points.

What Is WCF? Why Should We Use WCF?
Here, the first endpoint will transport a message in XML format over HTTP protocol and the second endpoint will transport the message in binary format over TCP protocol. Here, we don’t need to change the service code to configure these endpoints. Now, if we have a third client who needs a binary message over HTTP protocol, to satisfy that client requirement, all we need to do is to create a new endpoint.

So, we have a single service but then to satisfy the requirements of different clients, we are creating/configuring different endpoints.



European PHP Hosting - HostForLIFE.eu :: MySQL PHP MVC CRUD Without Framework

clock August 14, 2020 12:50 by author Peter

This tutorial is for beginners or students. I created a functionality to add, edit and delete a record in PHP with MVC logic without Framework. Also,  explained how to create an MVC pattern in PHP. I hope it will be helpful for you to add a data table in your program.

Building Our MVC Framework Pattern in PHP
You might be wondering why we would even need to create our own framework when there are already so many good choices out there. The reason for this is so that we can gain an understanding of the underlying principles of MVC.

As we learn more about these principles, we will grow in our understanding of why the excellent MVC frameworks do things the way they do. We are not learning how to create an application in Zend Framework, or in CakePHP. We are learning how MVC works, and by extension, how these frameworks have built upon (or deviated from) the way in which we would expect an MVC framework to be built.
Section 1

Config.php is used to connect the mysql database to create a connection parameter for mysql host,user,password and database name.
<?php 
class config   
{    
function __construct() { 
$this->host = "localhost"; 
$this->user  = "root"; 
$this->pass = "welcome"; 
$this->db = "mydb13"; 


?> 


A small part of the code in index.php is used to setup a controller object and call mvcHandler() to view the default page list.php.
<?php 
session_unset(); 
require_once  'controller/sportsController.php';         
$controller = new sportsController();    
$controller->mvcHandler(); 
?> 


In the model folder, create one class for table structure, its named sports and has field and message field to hold messages and data.
<?php 
class sports 

// table fields 
public $id; 
public $category; 
public $name; 
// message string 
public $id_msg; 
public $category_msg; 
public $name_msg; 
// constructor set default value 
function __construct() 

$id=0;$category=$name=""; 
$id_msg=$category_msg=$name_msg=""; 


?> 


Section 2
The second section is a sportsModel class structure. We are going to explain and show insertRecord(), updateRecord(),selectRecord() and insertRecord(). The sportsModel class is used to access the function sportsController. The sportsModel class constructor receives a mysql connection parameter to work with the database.
<?php 

class sportsModel 

// set database config for mysql 
function __construct($consetup) 

$this->host = $consetup->host; 
$this->user = $consetup->user; 
$this->pass =  $consetup->pass; 
$this->db = $consetup->db;                                 

// open mysql data base 
public function open_db() 

$this->condb=new mysqli($this->host,$this->user,$this->pass,$this->db); 
if ($this->condb->connect_error)  

die("Erron in connection: " . $this->condb->connect_error); 


// close database 
public function close_db() 

$this->condb->close(); 

// insert record 
public function insertRecord($obj){ } 
//update record 
public function updateRecord($obj){ } 
// delete record 
public function deleteRecord($id){ }    
// select record      
public function selectRecord($id){ } 


?> 


Section 3
Section 3 is the controller code part. The sportsController has mvcHandler() and the CRUD functions insert(), update(),delete() and list(). mvcHandler() receives request and execute. This request shows views according to call request by user.
// insert record 
public function insertRecord($obj) 

try 
{    
    $this->open_db(); 
    $query=$this->condb->prepare("INSERT INTO sports (category,name) VALUES (?, ?)"); 
    $query->bind_param("ss",$obj->category,$obj->name); 
    $query->execute(); 
    $res= $query->get_result(); 
    $last_id=$this->condb->insert_id; 
    $query->close(); 
    $this->close_db(); 
    return $last_id; 

catch (Exception $e)  

    $this->close_db();    
    throw $e; 


//update record 
public function updateRecord($obj) 

try 
{    
    $this->open_db(); 
    $query=$this->condb->prepare("UPDATE sports SET category=?,name=? WHERE id=?"); 
    $query->bind_param("ssi", $obj->category,$obj->name,$obj->id); 
    $query->execute(); 
    $res=$query->get_result();                        
    $query->close(); 
    $this->close_db(); 
    return true; 

catch (Exception $e)  

    $this->close_db(); 
    throw $e; 


// delete record 
public function deleteRecord($id) 
{    
try{ 
    $this->open_db(); 
    $query=$this->condb->prepare("DELETE FROM sports WHERE id=?"); 
    $query->bind_param("i",$id); 
    $query->execute(); 
    $res=$query->get_result(); 
    $query->close(); 
    $this->close_db(); 
    return true;     

catch (Exception $e)  

    $this->closeDb(); 
    throw $e; 
}        
}    
// select record      
public function selectRecord($id) 

try 

    $this->open_db(); 
    if($id>0) 
    {    
        $query=$this->condb->prepare("SELECT * FROM sports WHERE id=?"); 
        $query->bind_param("i",$id); 
    } 
    else 
    {$query=$this->condb->prepare("SELECT * FROM sports");    }        
     
    $query->execute(); 
    $res=$query->get_result();    
    $query->close();              
    $this->close_db();                 
    return $res; 

catch(Exception $e) 

    $this->close_db(); 
    throw $e;    

 


Section Four
Section four is the view part, when mvcHandler() receives a request and executes the request, it shows views for user. We have created three views in the view folder, which is insert, update and list, which all have HTML design. These views work with controller, and the controller works with model to get or set records in a database table.
<div class="wrapper">   
<div class="container-fluid">   
<div class="row">   
<div class="col-md-12">   
    <div class="page-header clearfix">   
        <a href="index.php" class="btn btn-success pull-left">Home</a>   
        <h2 class="pull-left">Sports Details</h2>   
        <a href="view/insert.php" class="btn btn-success pull-right">Add New Sports</a>   
    </div>   
    <?php   
        if($result->num_rows > 0){   
            echo "<table class='table table-bordered table-striped'>";   
                echo "<thead>";   
                    echo "<tr>";   
                        echo "<th>#</th>";                                           
                        echo "<th>Sports Category</th>";   
                        echo "<th>Sports Name</th>";   
                        echo "<th>Action</th>";   
                    echo "</tr>";   
                echo "</thead>";   
                echo "<tbody>";   
                while($row = mysqli_fetch_array($result)){   
                    echo "<tr>";   
                        echo "<td>" . $row['id'] . "</td>";                                           
                        echo "<td>" . $row['category'] . "</td>";   
                        echo "<td>" . $row['name'] . "</td>";   
                        echo "<td>";   
                        echo "<a href='index.php?act=update&id=". $row['id'] ."' title='Update Record' data-toggle='tooltip'><i class='fa fa-edit'></i></a>";   
                        echo "<a href='index.php?act=delete&id=". $row['id'] ."' title='Delete Record' data-toggle='tooltip'><i class='fa fa-trash'></i></a>";   
                        echo "</td>";   
                    echo "</tr>";   
                }   
                echo "</tbody>";                               
            echo "</table>";   
            // Free result set   
            mysqli_free_result($result);   
        } else{   
            echo "<p class='lead'><em>No records were found.</em></p>";   
        }   
    ?>   
</div>   
</div>           
</div>   
</div>   


Conclusion
This article showed and explained to beginners how to make an MVC framework pattern in PHP. You might be wondering why we would even need to create our own framework when there are already so many good choices out there. The reason for this is so we can gain an understanding of the underlying principles of MVC.



Europe SQL Hosting - HostForLIFE.eu :: Delete Duplicate Rows From a Table in MSSQL 2012

clock July 22, 2020 13:56 by author Peter

For every table, we tend to use a primary key or distinctive key for distinct values, however generally we'll encounter a problem with duplicate records. it's a significant issue with duplicate rows. thus we want to delete duplicate records to resolve it. So here i'll make an example to explain delete duplicate rows in MSSQL Hosting.

Example:
First we create a simple database with one table for membership that contains: a Member's ID, Membership type, Firstname,  Lastname and Birthday:
CREATE TABLE [dbo].[Membership](
[MemberID] [varchar](20) NOT NULL,
[MemberType] [int] NOT NULL,
[Firstname] [varchar](80) NOT NULL,
[Lastname] [varchar](80) NOT NULL,
[Birthday] [date] NOT NULL
) ON [PRIMARY]

Now, insert the following rows into this table:

INSERT INTO dbo.Membership (MemberID, Firstname, Lastname, MemberType, Birthday) VALUES
('001', 'Peter', 'Smith', 1, convert(datetime, '05/23/1988', 0))
INSERT INTO dbo.Membership (MemberID, Firstname, Lastname, MemberType, Birthday) VALUES
('002', 'Scott', 'Davidson', 1, convert(datetime, '07/10/1983', 0))
INSERT INTO dbo.Membership (MemberID, Firstname, Lastname, MemberType, Birthday) VALUES
('002', 'Scott', 'Davidson', 1, convert(datetime, '07/10/1983', 0))

INSERT INTO dbo.Membership (MemberID, Firstname, Lastname, MemberType, Birthday) VALUES
('003', 'Kevin', 'Richard', 1, convert(datetime, '04/24/1985', 0))

We currently have duplicated Scott Davidson’s entry (MemberID 2), with no clearly safe method of removing the duplicate, whereas leaving at least one entry intact. Now, imagine if you had a complete databse of information with a whole lot or thousands of duplicates. Fixing this by hand quickly becomes an impossible task!

To solve this, first we can add an column using the IDENTITY keyword so we currently have a unique method of addressing every row:
ALTER TABLE dbo.Membership ADD AUTOID INT IDENTITY(1,1)

We can then we can use:
SELECT * FROM dbo.Membership WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
FROM dbo.Membership GROUP BY MemberID)

Which will properly choose all duplicated records in our database (always worth checking before running the delete query!).  Once we are happy this is working for us, we can then run the delete query:

DELETE FROM dbo.Membership WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
FROM dbo.Membership GROUP BY MemberID)



Magento Hosting - HostForLIFE.eu :: How To Install Magento Security Patch?

clock July 1, 2020 13:18 by author Peter

Making money is serious business, and it does take time for every effort to nurture and mature. Online shopping is actually only a small part of the wilderness of e-commerce. Web shopping which includes online transactions stock, download the software directly from the web actually connecting businesses to consumers is only about 20% of the total e-commerce. In fact, more in the form of trade relations business to business that facilitates the process of purchasing between companies. Many people hope that the possible occurrence of micro-transactions that allow people to pay in the form of coins some thousand or hundred dollars to access content or games on the Internet. One CMS that is used to create an online shop is Magento.

Magento is a premium shopping platform that Provides a platform online store with reviews Reviews their hosting packages. Features on Magento especially reporting features. This online store also handles complex system of discounts and voucher systems that can be integrated with other systems. Magento is an online shop for professionals who need a shopping system with detailed reporting. Magento has two versions items, Community (Open Source) and Professional.

Magento released a new patch for the Community Edition 1.9 and Enterprise Edition 1.14 to address security issues, including remote code execution and information leak vulnerabilities.

Be sure to test the patch in a development environment first, as it can affect extensions and customizations :

You can download the patch for both Community Edition and Enterprise Edition from the following options:

  • Partners: Go to the Partner Portal, select Technical Resources and then select Download from the Enterprise Edition panel. Next, navigate to Magento Enterprise Edition > Patches & Support and look for the folder titled “Security Patches – July-October.”
  • Enterprise Edition Merchants: Go to My Account, select the Downloads tab, and then navigate to Magento Enterprise Edition > Support Patches. Look for the folder titled “Security Patches – October 2015” .Merchants can also upgrade to the latest version of the Enterprise Edition and receive the security fixes as part of the core code.
  • Community Edition Merchants: Patches for earlier versions of Community Edition can be found on the Community Edition download page (look for SUPEE-67.88) Merchants can also upgrade today to the latest version of the Community Edition and receive the security fixes as part of the core code.

Before installing the patch check whether old patches are installed correctly. Some patches depend on other patches to be installed already.

Simply unpack the archive and replace files on your store by uploading app/ and lib/ folders into your Magento root directory.
If you use PHP opcode caches (APC/XCache/eAccelerator) make sure to flush it after patching, otherwise code will continue to run from caches.

If you have SSH access, it would be simpler to install the patch. Before installing the patch make sure to disable Magento Compiler at System > Configuration > Tools > Magento Compiler and clear compiled cache (if compiler is used).

If you have no SSH access, then to apply to the patch, you can simply upgrade your installation to the latest Magento version.

After the patch is installed successfully, check whether all CMS , home page, category pages and landing pages are running correctly without any issues. Magento security patch Supee 6788 affects the page layout, transaction emails and order confirmation notifications.

The Magento security patch supee 6788 has introduced new permissions for  blocks, core variables on CMS pages, templates and extensions. You can add your blocks in the admin section under System -> Permissions -> Blocks, or via setup scripts adding to the permission_block table.
Also, check if any other pages or blocks or transactional emails have been affected.

HostForLIFE.eu Magento Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They 
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



European Visual Studio 2017 Hosting - HostForLIFE.eu :: Drawing rubber-band lines and shapes in VB.NET

clock June 19, 2020 12:57 by author Peter

 The lack of XOR Drawing feature in GDI+ was not certainly welcome in the programmer's community. I guess it will be hard to survive with this handicap. In spite of this, I would like to show how we can draw rubber-band lines and shapes in GDI+ with just a few lines of code.

     Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
    Dim size As Size = SystemInformation.PrimaryMonitorMaximizedWindowSize 
    bitmap = New Bitmap(size.Width, size.Height) 
    gB = Graphics.FromImage(bitmap) 
    Dim bckColor As Color = Me.BackColor 
    gB.Clear(bckColor) 
    End Sub 
    Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
    Dim p As Point = New Point(e.X, e.Y) 
    x0 = p.X 
    y0 = p.Y 
    drag = True 
    End Sub 
    Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
    Dim p As Point = New Point(e.X, e.Y) 
    x= p.X 
    y = p.Y 
    Dim cx As Integer = x - x0 
    Dim cy As Integer = y - y0 
    If drag Then 
    Dim gx As Graphics = CreateGraphics() 
    gx.DrawImage(bitmap, 0, 0) 
    gx.Dispose() 
    Dim g As Graphics = CreateGraphics() 
    Dim pen As Pen = New Pen(Color.Blue) 
    Select Case DrawMode 
    Case 1 
    g.DrawLine(pen, x0, y0, x, y) 
    Exit Select 
    Case 2 
    g.DrawEllipse(pen, x0, y0, cx, cy) 
    Exit Select 
    Case 3 
    g.DrawRectangle(pen, x0, y0, cx, cy) 
    Exit Select 
    End Select 
    g.Dispose() 
    pen.Dispose() 
    End If 
    End Sub 
    Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
    Dim cx As Integer = x - x0 
    Dim cy As Integer = y - y0 
    Dim pen As Pen = New Pen(Color.Blue) 
    Select Case DrawMode 
    Case 1 
    gB.DrawLine(pen, x0, y0, x, y) 
    Exit Select 
    Case 2 
    gB.DrawEllipse(pen, x0, y0, cx, cy) 
    Exit Select 
    Case 3 
    gB.DrawRectangle(pen, x0, y0, cx, cy) 
    Exit Select 
    End Select 
    drag = False 
    pen.Dispose() 
    End Sub 
    Private Sub Form1_Paint(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.PaintEventArgs) 
    Dim gx As Graphics = CreateGraphics() 
    gx.DrawImage(bitmap, 0, 0) 
    gx.Dispose() 
    End Sub 
    Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)button1.ForeColor = Color.Red 
    button2.ForeColor = Color.Black 
    button3.ForeColor = Color.Black 
    DrawMode = 1 
    End Sub 
    Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    button2.ForeColor = Color.Red 
    button1.ForeColor = Color.Black 
    button3.ForeColor = Color.Black 
    DrawMode = 2 
    End Sub 
    Private Sub button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    button3.ForeColor = Color.Red 
    button1.ForeColor = Color.Black 
    button2.ForeColor = Color.Black 
    DrawMode = 3 
    End Sub 
    Private Sub panel1_Paint(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.PaintEventArgs) 
    button1.ForeColor = Color.Red 
    button1.Focus() 
    End Sub



European Entity Framework Hosting - HostForLIFE.eu :: Efficient Data Modification with Entity Framework Core

clock April 24, 2020 06:47 by author Peter

A simple rule says that for optimal performance, we need to make as few database requests as possible. This is especially relevant for insert and update scenarios, where we sometimes need to work with thousands of objects. Sending those objects to the database one by one is usually significantly slower than in a batch. With tools like Entity LINQ we can easily write efficient data modification queries.

Efficient Data Modification With Entity Framework Core 

Let's analyze the possible cases:
    INSERT
    UPDATE (DELETE)
    Upsert (UPDATE or INSERT)

INSERT case optimizations

Insert multiple rows in a single statement. Assuming we have a collection of promotions, the following snippet inserts them in a single query:
    public void InsertBatch(IEnumerable<Promotions> promos) 
    { 
        var query = DbContext.Promotions.Query((Promotions promo) => 
        { 
            var set = [email protected]((promo.PromotionName, promo.Discount, promo.StartDate, promo.ExpiredDate)); 
     
            INSERT().INTO(set); 
            var r = OUTPUT(INSERTED<Promotions>()); 
            VALUES(set.RowsFrom(promos)); 
     
            return r; 
        }); 
     
        foreach (var promo in query) 
            Console.WriteLine((promo.PromotionId, promo.PromotionName, promo.Discount, promo.StartDate, promo.ExpiredDate)); 
    } 


INSERT INTO ... SELECT ...
 
This is a so-called bulk insert. In the case that the data is already in the database, it is much cheaper to avoid data pulling altogether. The operation can potentially be performed inside the database. The following snippet copies addresses from one table to another according to some criteria without a single byte to leave the database.
    var cities = new[] { "Santa Cruz", "Baldwin" }; 
     
    DbContext.Database.Query((Stores stores, Addresses address) => 
    { 
        var set = [email protected]((address.Street, address.City, address.State, address.ZipCode)); 
     
        INSERT().INTO(set); 
        SELECT((stores.Street, stores.City, stores.State, stores.ZipCode)); 
        FROM(stores); 
        WHERE(cities.Contains(stores.City)); 
    }); 


UPDATE case optimizations

A bulk update works when there is a need to update multiple rows in the same table. There is a special SQL construct for this case - UPDATE ... WHERE, which performs the update in a single query. Some databases, like SQL server, also support a more powerful UPDATE ... JOIN construct. Below we update all the tax configurations without pulling them to the application server:
    var one = 0.01M; 
    var two = 0.02M; 
    DbContext.Database.Query((Taxes taxes) => 
    { 
        UPDATE(taxes).SET(() => { 
                taxes.MaxLocalTaxRate += two; 
                taxes.AvgLocalTaxRate += one; 
            }); 
        WHERE(taxes.MaxLocalTaxRate == one); 
    }); 


Bulk delete, same idea for the delete case.

    private static void PrepareProductHistory(Products products) 
    { 
        var productHistory = ToTable<Products>(PRODUCT_HISTORY); 
     
        SELECT(products).INTO(productHistory); 
        FROM(products); 
     
        Semicolon(); 
    } 
     
    ... 
     
    var year = 2017; 
    DbContext.Database.Query((Products products) => 
    { 
        PrepareProductHistory(products); 
        var productHistory = ToTable<Products>(PRODUCT_HISTORY); 
     
        DELETE().FROM(productHistory); 
        WHERE(productHistory.ModelYear == year); 
    }); 


UPSERT optimization
Efficient Data Modification With Entity Framework Core
 
Upsert means UPDATE or INSERT in a single statement. In cases when a table has more than 1 unique constraint (in addition to PK), plain INSERT can fail on duplicate key. In those cases, we usually want to ignore, replace or combine some existing fields with new values. Most vendors support this capability, but using different syntax and providing different features.
 
MERGE
SQL Server and Oracle. In fact, this is the official standard. In its simplest form, it allows for the specification of what to do WHEN MATCHED, i.e. when there is a unique key collision, and what to do WHEN NOT MATCHED, i.e. we can INSERT safely.

    DbContext.Category.Query((Category category) =>   
    {   
        var staging = ToTable<Category>(CATEGORY_STAGING);   
       
        MERGE().INTO(category).USING(staging).ON(category == staging);   
       
        WHEN_MATCHED().THEN(MERGE_UPDATE().SET(() =>   
                {   
                    category.CategoryName = staging.CategoryName;   
                    category.Amount = staging.Amount;   
                }));   
       
        var set = categor[email protected]((category.CategoryId, category.CategoryName, category.Amount));   
        WHEN_NOT_MATCHED().THEN(MERGE_INSERT(set.ColumnNames(), VALUES(set.RowFrom(staging))));   
       
        Semicolon();   
       
        return SelectAll(category);   
    });    

As the picture says, it's trickier than it should be. There are many tutorials and official documentation.
 
INSERT ... ON DUPLICATE ... - MySQL and Postgres. The syntax is much simpler and allows us to handle the most common case only (compared to feature-packed MERGE):

    // There is a store which might already exist in the database. 
    // Should we add it or update? (PK is not always the only UNIQUE KEY) 
    newOrExisting.LastUpdate = DateTime.Now; 
     
    DbContext.Database.Query((Store store) => 
    { 
        var view = [email protected]((store.StoreId, store.AddressId, store.ManagerStaffId, store.LastUpdate)); 
        INSERT().INTO(view); 
        VALUES(view.RowFrom(newOrExisting)); 
        ON_DUPLICATE_KEY_UPDATE(() => store.LastUpdate = INSERTED_VALUES(store.LastUpdate)); 
    }); 

Batch/bulk updates are usually in the order of a magnitude faster than working with entities one by one. Optimizing those scenarios is usually an easy improvement.



SQL Server 2016 Hosting - HostForLIFE.eu :: Subqueries And Correlated Subqueries

clock April 15, 2020 09:53 by author Peter

Subqueries In SQL Server
Subqueries are enclosed in parentheses. Subquery is also called an inner query and the query which encloses that inner query is called an outer query. Many times subqueries can be replaced with joins.
select * from Employee where DepartmentID not in (select distinct DepartmentID from Department) 

Another example:
select Department_Name,(select count(*) from Employee where DepartmentID=d.DepartmentID) from Department as d; 

The above query is an example of using subquery in the select list. The above result can be achieved using join also; see the below query
select d.Department_Name,COUNT(e.empid) as empcount from Department d 
join Employee e on e.DepartmentID=d.DepartmentID 
group by d.Department_Name 
order by empcount; 


According to MSDN, you can nest up to 32 levels.

Columns present in subqueries cannot be used in the outer select list of a query.

Correlated Subqueries

If our subquery depends on the outer query for its value then it is called a Correlated Subquery. It means subquery depends on outer subquery. Correlated subqueries are executed for every single row executed by outer subqueries.

A correlated subquery can be executed independently,
select distinct Department_Name,(select count(*) from Employee where DepartmentID=d.DepartmentID group by DepartmentID) as empcount from Department as d order by empcount; 

What to choose for performance --  Subquery or Join?
According to MSDN, there is no big difference between queries that use sub-queries and joins.

But in some cases, we need to check the performance, and Join produces better performance because the nested query must be processed for each result of the outer query. In such cases, JOIN will perform better.

In general, JOIN works faster as compared to subqueries but in reality, it will depend on the execution plan generated by the SQL Server. If the SQL server generates the same execution plan then you will get the same result.



Magento Hosting - HostForLIFE.eu :: How to Getting A Products URL on Magento?

clock April 3, 2020 08:14 by author Peter

In this post, I will show you how to get a products URL on Magento. There is 3 methods you can use, all of which are in Mage_Catalog_Model_Product. And here is the code:
public function getUrlPath($category=null)
public function getUrlInStore($params = array())
public function getProductUrl($useSid = null)

The simplest way to explain is to just show the results of many calls. Given a product whose URL key is scott-large-coffee-table-set-multicolour upon the domain of http :// created. local the results are :
$product->getUrlPath();
    'scott-large-coffee-table-set-multicolour'
$product->getUrlPath($category);
    'tables/scott-large-coffee-table-set-multicolour'
// you cannot stop this method adding ___store to the URL, even by setting _store_to_url to false
$product->getUrlInStore();
    'http://made.local/tables/scott-large-coffee-table-set-multicolour?___store=default'
// you cannot stop this method adding ___store to the URL, even by setting _store_to_url to false
// note - see the "using _ignore_category" section below for an arguable bug with using this param
$product->getUrlInStore(array('_ignore_category' => true));
    'http://made.local/scott-large-coffee-table-set-multicolour?___store=default'
$product->getProductUrl();
    'http://made.local/tables/scott-large-coffee-table-set-multicolour'
$product->getProductUrl(true);
    'http://made.local/tables/scott-large-coffee-table-set-multicolour'


To discover what some other params could be passed to getUrlInStore (), notice URL Route Parameters. Using _ignore_category. The brief version, I wouldn't use this param, and rather use Mage: getUrl ($product-getUrlPath ())

In case you first fetch a products URL that contains the category, then use a similar product instance to commit to fetch a non-category URL, you'll rather both times obtain a URL that includes the category, begin to see the below code :
$product = Mage::getModel('catalog/product');
$product->getUrlInStore();
    'http://made.local/sofas/peter-2-seater-sofa-blue?___store=default'
$product->getUrlInStore(array('_ignore_category' => true));
    'http://made.local/sofas/peter-2-seater-sofa-blue?___store=default'
$product = Mage::getModel('catalog/product');
$product->getUrlInStore(array('_ignore_category' => true));
    'http://made.local/peter-2-seater-sofa-blue?___store=default'

The problem lies using the request_path key upon the $product model, that the Mage_Catalog_Model_Product_Url : : getUrl () sets, to become a cached worth for an otherwise intensive method of resolving a URL rewrite to an item inside a category.

To solve this, unset request_path first, as beneath :
$product->unsRequestPath();
$product->getUrlInStore(array('_ignore_category' => true));
    'http://made.local/peter-2-seater-sofa-blue?___store=default'

Note which any technique outlined in the top of the card that leads to the category to be present inside the returned URL can have a similar effect of caching the category.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in