Wednesday, December 28, 2016

maybe backup entity framework migration history manual

SELECT * into [backup_db].[dbo].[migrations]
  FROM original_db.dbo.__MigrationHistory

after error

  insert into original.dbo.__MigrationHistory
  select * from [backup_db].[dbo].[migrations]

how to use EntityFramework in WinForms application beginning

/*WinForms application, EntityFramework ашиглах жишээ*/

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Database.SetInitializer<DbContextCurrentAssets>(new DbContextCurrentAssetsInitializer());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.UserSkins.BonusSkins.Register();
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");//Money Twins//DevExpress Style
Application.Run(new frmLogin());
}
}
/*********************************************************************************************************************************/
namespace HO.CURRENT.ASSETS
{
/// <summary>
/// DbContextCurrentAssets -г үүсгэсний дараа Seed дуудагдаж өгөгдөл дээрх анхны утгыг оруулах
/// боломжтой болох ба DropCreateDatabaseIfModelChanges шалтгаалж дахин програмд дуудагдахгүй.
/// </summary>
public class DbContextCurrentAssetsInitializer : DropCreateDatabaseIfModelChanges<DbContextCurrentAssets>
{
protected override void Seed(DbContextCurrentAssets context)
{
base.Seed(context);
DbDefaultData.Initializer(context);
}
}
/// <summary>
/// DbHelper = new DbHelper<DbContextCurrentAssets>(serverName);
/// int ret = DbHelper.list<UserInfo>().Count();
/// Үед хамгийн түрүүнд дуудагдах ба DropCreateDatabaseIfModelChanges ямар байхаас шалтгаална.
/// </summary>
public class DbContextCurrentAssets : DbContext
{
public DbContextCurrentAssets()
: base(AppConfig.GetConnectionString("."))
{
}
public DbContextCurrentAssets(string connStr)
: base(connStr)
{
}
/// <summary>
/// TContext db = instance();
/// DbSet sets = db.Set(typeof(TEntity));
/// IQueryable<TEntity> list = sets.OfType<TEntity>();
/// Үед байнга дуудагдаж ажиллана.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//...or do it manually below. For example,
//modelBuilder.Configurations.Add(new UserMap());
//modelBuilder.Configurations.Add(new RoleMap());
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public DbSet<CountryInfo> CountryInfoes { get; set; }
public DbSet<CityInfo> CityInfoes { get; set; }
public DbSet<SexInfo> SexInfoes { get; set; }
public DbSet<UnitInfo> UnitInfoes { get; set; }
public DbSet<UserInfo> UserInfoes { get; set; }
public DbSet<RoleInfo> RoleInfoes { get; set; }
public DbSet<UserRoleInfo> UserRoleInfoes { get; set; }
public DbSet<RoleWindowInfo> RoleWindowInfoes { get; set; }
..........................
..........................
}
}

/****************************************************************************************************/


хэрэв connStr ээ өөрсдөө нууцлан (_ConnectionString дэх user, pass аа нууц файлаас авч) generate ( учир нь апп програм аль ч ком дээр суух учир db,user,pass аа нууцлах шаардлагатай ) хийх бол нэг иймэрхүү функц ашиглаж болно.! 

private TContext instance()
{
if (_ContextObject is DbContext)
{
return _ContextObject;
}

try
{
Type type = typeof(TContext);
Assembly assembly = type.Assembly;

ConstructorInfo[] ConstructorInformation = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);

object[] args = new object[] { _ConnectionString };

_ContextObject = (TContext)assembly.CreateInstance(type.FullName, true
, BindingFlags.Instance | BindingFlags.Public
, null, args, System.Globalization.CultureInfo.CurrentCulture
, null);

return _ContextObject;
}
catch (Exception ex)
{
MessageBox.Show("Өгөгдлийн сангийн класс үүсгэх үед асуудал гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
, "Системийн Алдаа (DbHelper.instance)", MessageBoxButtons.OK, MessageBoxIcon.Error);

return null;
}
}



<connectionStrings>
<add name="DbContextCurrentAssets" connectionString="Data Source={0};Initial Catalog=DbCurrentAssets;User ID={1};Password={2};MultipleActiveResultSets=True;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>

Devexpress show ContextMenu in GridView Item

ContextMenuStrip cms = new ContextMenuStrip();
            ToolStripItem tsi = new ToolStripMenuItem("Мэдээлэл", null, (s, e) =>
            {
                if (DataModel != null)
                {
                    GridItemMetaInfo f = new GridItemMetaInfo(DataModel);
                    f.Show();
                }
            });
            cms.Items.Add(tsi);
            GridItemContextMenu = cms;

/*GridView*/


private void Grd_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            showGridItemContextMenu((GridView)sender);
        }

        private void showGridItemContextMenu(GridView view)
        {
            if (view.FocusedColumn == null) return;

            int ri = view.FocusedRowHandle;
            int vi = view.FocusedColumn.VisibleIndex;
            GridViewInfo info = (GridViewInfo)view.GetViewInfo();

            GridCellInfo cell = info.GetGridCellInfo(ri, view.FocusedColumn);
            System.Drawing.Rectangle r = cell.Bounds;

            System.Drawing.Point point = new System.Drawing.Point(r.X + r.Width, r.Y + r.Height);
            GridItemContextMenu.Show(view.GridControl, point);
        }

        private void showGridItemContextMenu(GridView view, System.Drawing.Point location)
        {
            GridHitInfo hitInfo = view.CalcHitInfo(location);
            if (hitInfo.InRow)
            {
                view.FocusedRowHandle = hitInfo.RowHandle;
                GridItemContextMenu.Show(view.GridControl, location);
            }
        }

Thursday, June 2, 2016

ajax page for crawler using history.pushState and window.onpopstate

<!DOCTYPE html>
<!-- saved from url=(0045)http://html5doctor.com/demos/history/whiskers -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
  <title>test!</title>
  <style>
    html { background-color:#ddd; }
    body { margin:1em auto; max-width:600px; background-color:#fff; border:solid 1px #aaa; padding:15px; font-family:Georgia,serif; }
    h1 { font-family:Helvetica,Arial,sans-serif; float:left; width:30%; margin:0; }
    nav { display:block; float:right; width:45%;}
    ul { list-style:none; padding:0; margin:0; }
    li { display:inline-block; padding:0; border-right:solid 1px #aaa; margin:.5em 0 0; }
    li:last-child { border-right:0; }
    a { color:rgb(0,144,210); padding:.2em 0.5em; }
    a:hover { text-decoration:none; }
    #content { clear:left; float:left; width:45%; margin-right:10%; line-height:1.4em; }
    #photo { float:right; width:45%; margin-top:1em; }
    .cf:before, .cf:after { content:""; display:table; }
    .cf:after { clear:both; }
  </style>
</head>

<body class="cf">
  <h1>test!</h1>

  <nav>
    <ul class="cf">
      <li><a href="/fluffy">Fluffy</a></li>
      <li><a href="/socks">Socks</a></li>
      <li><a href="/whiskers">Whiskers</a></li>
      <li><a href="/bob">Bob</a></li>
    </ul>
  </nav>

  <p id="content">content!</p>

  <img src="" alt="A heartbreakingly cute kitten!" id="photo">

  <script>
    // Not the most elegant code but fit enough for this example. Enjoy the kitten goodness!
    var contentEl = document.getElementById('content'),
        photoEl = document.getElementById('photo'),
        linkEls = document.getElementsByTagName('a'),
        cats = {
          fluffy: {
            content: 'Fluffy!',
            photo: 'http://placekitten.com/200/200'
          },
          socks: {
            content: 'Socks!',
            photo: 'http://placekitten.com/280/280'
          },
          whiskers: {
            content: 'Whiskers!',
            photo: 'http://placekitten.com/350/350'
          },
          bob: {
            content: 'Just Bob.',
            photo: 'http://placekitten.com/320/270'
          }
        };

    // Switcheroo!
    function updateContent(data) {
      if (data == null)
        return;

      contentEl.textContent = data.content;
      photoEl.src = data.photo;
    }

    // Attach event listeners
    for (var i = 0, l = linkEls.length; i < l; i++) {
      linkEls[i].addEventListener('click', function (event) {
      var cat = event.target.getAttribute('href').split('/').pop();
 var data = cats[cat] || null; // In reality this could be an AJAX request

      updateContent(data);

      // Add an item to the history log
 document.title = event.target.textContent;
      history.pushState(data, event.target.textContent, event.target.href);

      return false;
    });
    }

    // Revert to a previously saved state
    window.addEventListener('popstate', function(event) {
      console.log('popstate fired!');

      updateContent(event.state);
    });

    // Store the initial content so we can revisit it later
    history.replaceState({
      content: contentEl.textContent,
      photo: photoEl.src
    }, document.title, document.location.href);
  </script>



</body></html>

Sunday, May 15, 2016

angularjs too many request queue using promise

angularjs дээр олон тооны request илгээхдээ хүсэлт очиж байгааг дараалийг удирдаж дэс дараалалтай яаж илгээх вэ?

<div ng-app>
  <h2>$q test</h2>
  <div ng-controller="TodoCtrl">
      <div ng-bind="'Promise1: ' + Promise1"></div>
      <div ng-bind="'Promise2: ' + Promise2"></div>
      <div ng-bind="'Promise3: ' + Promise3"></div>
      <div ng-bind="'Promise4: ' + Promise4"></div>
      <div ng-bind="'Promise5: ' + Promise5"></div><br />
      <div ng-bind="'Status1: ' + Status1"></div>
      <div ng-bind="'Status2: ' + Status2"></div>
  </div>

</div>

JS:

function TodoCtrl($scope, $q, $timeout) {
    function createPromise(name, timeout, willSucceed) {
        $scope[name] = 'Running';
        var deferred = $q.defer();
        $timeout(function() {
            if (willSucceed) {
                $scope[name] = 'Completed';
                deferred.resolve(name);
            } else {
                $scope[name] = 'Failed';
                deferred.reject(name);
            }
        }, timeout * 1000);
        return deferred.promise;
    }
    
    // Create 5 promises
    var promises = [];
    var names = [];
    for (var i = 1; i <= 5; i++) {
        var willSucceed = true;
        if (i == 2) willSucceed = false;
        promises.push(createPromise('Promise' + i, i, willSucceed));
    }
    
    // Wait for all promises    
    $scope.Status1 = 'Waiting';
    $scope.Status2 = 'Waiting';
    $q.all(promises).then(
        function() { 
            $scope.Status1 = 'Done'; 
        }, 
        function() { 
            $scope.Status1 = 'Failed'; 
        }
    ).finally(function() {
        $scope.Status2 = 'Done waiting';
    });
}

result:

Promise1: Completed
Promise2: Failed
Promise3: Completed
Promise4: Completed
Promise5: Completed

Status1: Failed
Status2: Done waiting

Wednesday, May 4, 2016

php data array echo to excel file

<?PHP
  $data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
    array("firstname" => "James", "lastname" => "Brown", "age" => 31),
    array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
    array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
    array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
    array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
  );

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // file name for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\n";
      $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\n";
  }

  exit;
?>

Thursday, April 28, 2016

codeigniter my custom captcha controller, view

$config['compress_output'] = TRUE;
****************************************************************

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class captcha extends HO_Admin {

    public function __construct() {
        parent::__construct(FALSE);

        //image captcha library
        $this->load->library('HO/HiimelCaptcha', array($this), 'captcha');
    }

    public function image() {
        $this->xhr_protect();

        header("Content-type: image/jpeg");

        $arr = $this->captcha->createImage(6);
        $im = reset(array_values($arr));
        ob_start();
        imagejpeg($im);
        $this->output->cache(0);
        $this->output->set_output('data:image/jpeg;base64,' . base64_encode(ob_get_clean()));
    }

}

******************************************

if ($this->web_cache_minute > 0) {
                $this->output->cache($this->web_cache_minute);
            }
            $this->output->set_output($this->web->page());

********************************************

<div class="captcha">
                <div class="detail">
                    <div class="img">
                        <img src="" alt="" title="captcha">
                    </div>
                    <div class="inp">
                        <input type="text" maxlength="10" id="captcha_code" name="captcha_code">
                        <label>Дуурайж бичээрэй!</label>
                    </div>
                </div>
            </div>
            <script>
                (function reloadCaptchaImg(capimg) {
                    var link = '<?php echo admin_url('captcha/image?'); ?>' + getTimeAsLong();
                    $.ajax({
                        url: link,
                        success: function (result) {
                            var par = capimg.parent();
                            capimg.remove();
                            capimg = $('<img src="' + result + '"/>');
                            capimg.appendTo(par);
                            capimg.animate({'opacity': '1'}, {
                                duration: 300
                            });
                        }
                    });
                })($('.captcha img'));
            </script>

Thursday, April 14, 2016

jquery accordion with sortable for navigation menu

HTML


<div id="accordion">    
    <div>        
        <h3><a href="#">Section 1</a></h3>        
        <div>            
            <p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.</p>        
        </div>    
    </div>    
    <div>        
        <h3><a href="#">Section 2</a></h3>        
        <div>            
            <p>Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In suscipit faucibus urna. </p>        
        </div>    
    </div>    
    <div>         <h3><a href="#">Section 3</a></h3>         <div>             <p>Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis. Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui. </p>             <ul>                 <li>List item one</li>                 <li>List item two</li>                 <li>List item three</li>             </ul>         </div>     </div>     <div>         <h3><a href="#">Section 4</a></h3>         <div>             <p>Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia mauris vel est. </p><p>Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>         </div>     </div> </div>



JS

var stop = false;

$("#accordion h3").click(function(event) {
    $(this).closest('div').prependTo('#accordion');
});

$("#accordion").accordion({
    header: "> div > h3"
}).sortable({
    axis: "y",
    handle: "h3"
});