Exemplo n.º 1
0
        public ShowMessages(RC.Gmail.GmailAtomFeed.AtomFeedEntryCollection aGMailFeed)
        {
            InitializeComponent();

            setGridViewStyle();

            try
            {
                if (aGMailFeed.Count != 0)
                {
                    for (int i = 0; i < aGMailFeed.Count; i++)
                    {
                        gridViewMessages.Rows.Add(i + 1, aGMailFeed[i].Subject, aGMailFeed[i].FromEmail);
                        gridViewMessages.Rows[gridViewMessages.Rows.Count - 1].Tag = aGMailFeed[i].Link;
                    }
                    labelNoNewMessages.Visible = false;
                }
                else
                {
                    Melissa.Say("You have no new messages!");
                    gridViewMessages.Visible = false;
                    labelNoNewMessages.Visible = true;
                }
            }
            catch { }
        }
Exemplo n.º 2
0
        public MessagingManager(	AuthInfo authInfo,
									EmailServiceDescription emailServiceDescription,
									OpenPGPRing openPgpRing,
									XmppServiceDescription xmppServiceDescription,
									OTRKeyRing otrKeyring,
									ContactManager contactManager,
									Logger logger,
									int inboxCheckIntervall,
									bool isInMinutes)
        {
            m_AuthInfo = authInfo;
            m_EmailServiceDescription = emailServiceDescription;
            m_OpenPgpRing = openPgpRing;
            m_XmppServiceDescription = xmppServiceDescription;
            m_OtrKeyRing = otrKeyring;
            m_Logger = logger;
            m_InboxCheckIntervall = inboxCheckIntervall;
            m_bIsIntervallInMinutes = isInMinutes;
            m_ConversationManager = new ConversationManager ();
            m_ContactManager = contactManager;

            RC rcMail = initEmailManager();
            RC rcXmpp = initXmppManager();
            m_Status = RC.RC_OK;
            if (rcMail != RC.RC_OK) {
                m_Status = RC.RC_COULD_NOT_INIT_EMAIL;
            }

            if (rcXmpp != RC.RC_OK) {
                m_Status = RC.RC_COULD_NOT_INIT_XMPP;
            }
        }
Exemplo n.º 3
0
 private static void find(RC A, RC B, RC C, RC D, RC K, int i, int j, out char symbol)
 {
     if (A.r == i && A.c == j)
     {
         symbol = 'A';
     }
     else if (B.r == i && B.c == j)
     {
         symbol = 'B';
     }
     else if (C.r == i && C.c == j)
     {
         symbol = 'C';
     }
     else if (D.r == i && D.c == j)
     {
         symbol = 'D';
     }
     else if (K.r == i && K.c == j)
     {
         symbol = 'K';
     }
     else if ((i + j) % 2 == 0)
     {
         symbol = '+';
     }
     else
     {
         symbol = '-';
     }
 }
Exemplo n.º 4
0
		public static int PackagesFromDebianFile(string filename, RC.Channel channel, RC.PackageDelegate cb) {
			IntPtr filename_as_native = GLib.Marshaller.StringToPtrGStrdup (filename);
			RCSharp.PackageDelegateWrapper cb_wrapper = new RCSharp.PackageDelegateWrapper (cb);
			int raw_ret = rc_extract_packages_from_debian_file(filename_as_native, channel == null ? IntPtr.Zero : channel.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero);
			int ret = raw_ret;
			GLib.Marshaller.Free (filename_as_native);
			return ret;
		}
Exemplo n.º 5
0
		public static int PackagesFromDirectory(string path, RC.Channel channel, RC.Packman packman, bool recursive, RC.PackageDelegate cb) {
			IntPtr path_as_native = GLib.Marshaller.StringToPtrGStrdup (path);
			RCSharp.PackageDelegateWrapper cb_wrapper = new RCSharp.PackageDelegateWrapper (cb);
			int raw_ret = rc_extract_packages_from_directory(path_as_native, channel == null ? IntPtr.Zero : channel.Handle, packman == null ? IntPtr.Zero : packman.Handle, recursive, cb_wrapper.NativeDelegate, IntPtr.Zero);
			int ret = raw_ret;
			GLib.Marshaller.Free (path_as_native);
			return ret;
		}
Exemplo n.º 6
0
		public static int PackagesFromUndumpBuffer(out byte data, int len, RC.ChannelAndSubdFn channel_callback, RC.PackageDelegate package_callback, RC.PackageMatchDelegate lock_callback) {
			RCSharp.ChannelAndSubdFnWrapper channel_callback_wrapper = new RCSharp.ChannelAndSubdFnWrapper (channel_callback);
			RCSharp.PackageDelegateWrapper package_callback_wrapper = new RCSharp.PackageDelegateWrapper (package_callback);
			RCSharp.PackageMatchDelegateWrapper lock_callback_wrapper = new RCSharp.PackageMatchDelegateWrapper (lock_callback);
			int raw_ret = rc_extract_packages_from_undump_buffer(out data, len, channel_callback_wrapper.NativeDelegate, package_callback_wrapper.NativeDelegate, lock_callback_wrapper.NativeDelegate, IntPtr.Zero);
			int ret = raw_ret;
			return ret;
		}
Exemplo n.º 7
0
 public static RC ApiExit(Context ctx, RC rc)
 {
     // If the ctx handle is not NULL, then we must hold the connection handle mutex here. Otherwise the read (and possible write) of db->mallocFailed is unsafe, as is the call to sqlite3Error().
     Debug.Assert(ctx == null || MutexEx.Held(ctx.Mutex));
     if (ctx != null && (ctx.MallocFailed || rc == RC.IOERR_NOMEM))
     {
         Error(ctx, RC.NOMEM, null);
         ctx.MallocFailed = false;
         rc = RC.NOMEM;
     }
     return (RC)((int)rc & (ctx != null ? ctx.ErrMask : 0xff));
 }
Exemplo n.º 8
0
		protected virtual void OnSubworldRemoved (RC.World subworld)
		{
			GLib.Value ret = GLib.Value.Empty;
			GLib.ValueArray inst_and_params = new GLib.ValueArray (2);
			GLib.Value[] vals = new GLib.Value [2];
			vals [0] = new GLib.Value (this);
			inst_and_params.Append (vals [0]);
			vals [1] = new GLib.Value (subworld);
			inst_and_params.Append (vals [1]);
			g_signal_chain_from_overridden (inst_and_params.ArrayPtr, ref ret);
			foreach (GLib.Value v in vals)
				v.Dispose ();
		}
Exemplo n.º 9
0
 //public static void Error(Context ctx, RC rc, int noString) { Error(ctx, rc, (rc == 0 ? null : string.Empty)); }
 public static void Error(Context ctx, RC rc, string fmt, params object[] args)
 {
     if (ctx != null && (ctx.Err != null || (ctx.Err = Vdbe.ValueNew(ctx)) != null))
     {
         ctx.ErrCode = rc;
         if (fmt != null)
         {
             string z = C._vmtagprintf(ctx, fmt, args);
             Vdbe.ValueSetStr(ctx.Err, -1, z, TEXTENCODE.UTF8, C.DESTRUCTOR_DYNAMIC);
         }
         else
             Vdbe.ValueSetStr(ctx.Err, 0, null, TEXTENCODE.UTF8, C.DESTRUCTOR_STATIC);
     }
 }
Exemplo n.º 10
0
    public Form1()
    {
        scene = new Scene();
            scene.redraw += new EventHandler(scene_redraw);

            InitializeComponent();

            simpleOpenglControl1.InitializeContexts();
            scene.Initialize();
            Otros.LoadTexture();
            scene.element=new Lugar();//new Base111(new Point3D(0,-2.6,-20),7,new float[]{1.0f,0.4f,0.2f,1.0f});
            rc=new RC(this);
            rc.Show();
    }
Exemplo n.º 11
0
 internal void ptrmapPutOvflPtr(byte[] pCell, ref RC pRC)
 {
     if (pRC != 0)
         return;
     var info = new CellInfo();
     Debug.Assert(pCell != null);
     btreeParseCellPtr(pCell, ref info);
     Debug.Assert((info.nData + (this.HasIntKey ? 0 : info.nKey)) == info.nPayload);
     if (info.iOverflow != 0)
     {
         Pgno ovfl = ConvertEx.Get4(pCell, info.iOverflow);
         this.Shared.ptrmapPut(ovfl, PTRMAP.OVERFLOW1, this.ID, ref pRC);
     }
 }
Exemplo n.º 12
0
 internal RC pager_error(RC rc)
 {
     var rc2 = (RC)((int)rc & 0xff);
     Debug.Assert(rc == RC.OK ||
     #if SQLITE_OMIT_MEMORYDB
     0==MEMDB
     #else
      0 == this.memDb
     #endif
     );
     Debug.Assert(this.errCode == RC.FULL || this.errCode == RC.OK || ((int)this.errCode & 0xff) == (int)RC.IOERR);
     if (rc2 == RC.FULL || rc2 == RC.IOERR)
     {
         this.errCode = rc;
         this.eState = PAGER.ERROR;
     }
     return rc;
 }
Exemplo n.º 13
0
        public uint[] OverflowIDs; // Cache of overflow page locations

        #endif

        #region Methods

        // was:sqlite3BtreeCursorZero
        public void Zero()
        {
            Next = null;
            Prev = null;
            KeyInfo = null;
            RootID = 0;
            _cachedRowID = 0;
            Info = new MemPage.CellInfo();
            Writeable = false;
            AtLast = false;
            ValidNKey = false;
            State = 0;
            Key = null;
            NKey = 0;
            SkipNext = 0;
            #if !SQLITE_OMIT_INCRBLOB
            IsIncrblob = false;
            OverflowIDs = null;
            #endif
            PageID = 0;
        }
Exemplo n.º 14
0
Arquivo: SysEx.cs Projeto: BclEx/GpuEx
        public static RC Config(CONFIG op, params object[] args)
        {
            // sqlite3_config() shall return SQLITE_MISUSE if it is invoked while the SQLite library is in use.
            if (_GlobalStatics.IsInit)
            {
                return(SysEx.MISUSE_BKPT());
            }
            RC rc = RC.OK;

            switch (op)
            {
#if THREADSAFE
            // Mutex configuration options are only available in a threadsafe compile.
            case CONFIG.SINGLETHREAD:
            {         // Disable all mutexing
                _GlobalStatics.CoreMutex = false;
                _GlobalStatics.FullMutex = false;
                break;
            }

            case CONFIG.MULTITHREAD:
            {         // Disable mutexing of database connections, Enable mutexing of core data structures
                _GlobalStatics.CoreMutex = true;
                _GlobalStatics.FullMutex = false;
                break;
            }

            case CONFIG.SERIALIZED:
            {         // Enable all mutexing
                _GlobalStatics.CoreMutex = true;
                _GlobalStatics.FullMutex = true;
                break;
            }

            case CONFIG.MUTEX:
            {         // Specify an alternative mutex implementation
                //_GlobalStatics.Mutex = (sqlite3_mutex_methods)args[0];
                break;
            }

            case CONFIG.GETMUTEX:
            {         // Retrieve the current mutex implementation
                //args[0] = _GlobalStatics.Mutex;
                break;
            }
#endif
            case CONFIG.MALLOC:
            {         // Specify an alternative malloc implementation
                //_GlobalStatics.m = *va_arg(args, sqlite3_mem_methods*);
                break;
            }

            case CONFIG.GETMALLOC:
            {         // Retrieve the current malloc() implementation
                //if (_GlobalStatics.m.xMalloc==0) sqlite3MemSetDefault();
                //args[0]= _GlobalStatics.m;
                break;
            }

            case CONFIG.MEMSTATUS:
            {         // Enable or disable the malloc status collection
                _GlobalStatics.Memstat = (bool)args[0];
                break;
            }

            case CONFIG.SCRATCH:
            {         // Designate a buffer for scratch memory space
                _GlobalStatics.Scratch     = (byte[][])args[0];
                _GlobalStatics.ScratchSize = (int)args[1];
                _GlobalStatics.Scratchs    = (int)args[2];
                break;
            }

#if ENABLE_MEMSYS3 || ENABLE_MEMSYS5
            case CONFIG_HEAP: {
                // Designate a buffer for heap memory space
                _GlobalStatics.Heap.data   = va_arg(args, void *);
                _GlobalStatics.Heap.length = va_arg(args, int);
                _GlobalStatics.MinReq      = va_arg(ap, int);
                if (_GlobalStatics.MinReq < 1)
                {
                    _GlobalStatics.MinReq = 1;
                }
                else if (SysEx_GlobalStatics.MinReq > (1 << 12))       // cap min request size at 2^12
                {
                    _GlobalStatics.MinReq = (1 << 12);
                }
                if (!_GlobalStatics.Heap.data)
                {
                    // If the heap pointer is NULL, then restore the malloc implementation back to NULL pointers too.  This will cause the malloc to go back to its default implementation when sqlite3_initialize() is run.
                    memset(&_GlobalStatics.m, 0, sizeof(_GlobalStatics.m));
                }
                else
                // The heap pointer is not NULL, then install one of the mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor ENABLE_MEMSYS5 is defined, return an error.
#if ENABLE_MEMSYS3
                { _GlobalStatics.m = sqlite3MemGetMemsys3(); }
#endif
#if ENABLE_MEMSYS5
                { _GlobalStatics.m = sqlite3MemGetMemsys5(); }
#endif
                { break; }
            }
#endif
            case CONFIG.LOOKASIDE:
            {
                _GlobalStatics.LookasideSize = (int)args[0];
                _GlobalStatics.Lookasides    = (int)args[1];
                break;
            }

            case CONFIG.LOG:
            {         // Record a pointer to the logger function and its first argument. The default is NULL.  Logging is disabled if the function pointer is NULL.
                // MSVC is picky about pulling func ptrs from va lists.
                // http://support.microsoft.com/kb/47961
                _GlobalStatics.Log    = (Action <object, int, string>)args[0];
                _GlobalStatics.LogArg = (object)args[1];
                break;
            }

            case CONFIG.URI:
            {
                _GlobalStatics.OpenUri = (bool)args[0];
                break;
            }

#if ENABLE_SQLLOG
            case CONFIG.SQLLOG: {
                _GlobalStatics.Sqllog    = (Action <object, TagBase, int, string>)args[0];;
                _GlobalStatics.SqllogArg = (object)args[1];
                break;
            }
#endif
            default:
            {
                rc = RC.ERROR;
                break;
            }
            }
            return(rc);
        }
Exemplo n.º 15
0
		public static string StatusToString(RC.PackageStatus status) {
			IntPtr raw_ret = rc_package_status_to_string((int) status);
			string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
			return ret;
		}
Exemplo n.º 16
0
        private static void AddCommentRecentChange(DateTime timestamp, PageBE page, UserBE user, DekiResource summary, CommentBE comment, RC rcType)
        {
            var resources = DekiContext.Current.Resources;

            //TODO MaxM: Consider truncating summary
            DbUtils.CurrentSession.RecentChanges_Insert(timestamp, page, user, resources.Localize(summary), 0, rcType, 0, string.Empty, false, 0);
        }
Exemplo n.º 17
0
 // <p style='font-style:italic;'>Since 1.0.32 (Release 9.3)</p><p>Creates a bot extension. Please note: Bot extension is always created in Enabled status, no welcome email is sent.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>EditAccounts</td><td>Viewing and updating user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>API Group</h4><p>Medium</p>
 public Task <BotExtensionCreation> Post(object parameters)
 {
     return(RC.Post <BotExtensionCreation>(Endpoint(true), parameters));
 }
Exemplo n.º 18
0
        internal override void End()
        {
            base.End();

            RC.EndProfilingBlock();
        }
 // <p style='font-style:italic;'>Since 1.0.31 (Release 9.2)</p><p>Returns the list of users requested.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadAccounts</td><td>Viewing user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>API Group</h4><p>Medium</p>
 public Task <GetUserListResponse> Get()
 {
     return(RC.Get <GetUserListResponse>(Endpoint(true), null));
 }
Exemplo n.º 20
0
        public IEnumerable <AccountingStockReportViewModel> GetStockQuery(string ctg, string unitcode, DateTime?datefrom, DateTime?dateto, int offset)
        {
            DateTime DateFrom = datefrom == null ? new DateTime(1970, 1, 1) : (DateTime)datefrom;
            DateTime DateTo   = dateto == null ? DateTime.Now : (DateTime)dateto;
            var      PPAwal   = (from a in dbContext.GarmentUnitReceiptNotes
                                 join b in dbContext.GarmentUnitReceiptNoteItems on a.Id equals b.URNId
                                 join d in dbContext.GarmentDeliveryOrderDetails on b.POId equals d.POId
                                 join f in dbContext.GarmentInternalPurchaseOrders on b.POId equals f.Id
                                 join e in dbContext.GarmentReceiptCorrectionItems on b.Id equals e.URNItemId into RC
                                 from ty in RC.DefaultIfEmpty()
                                 join c in dbContext.GarmentUnitExpenditureNoteItems on b.UENItemId equals c.Id into UE
                                 from ww in UE.DefaultIfEmpty()
                                 join r in dbContext.GarmentUnitExpenditureNotes on ww.UENId equals r.Id into UEN
                                 from dd in UEN.DefaultIfEmpty()
                                 where d.CodeRequirment == (String.IsNullOrWhiteSpace(ctg) ? d.CodeRequirment : ctg) &&
                                 a.IsDeleted == false && b.IsDeleted == false
                                 //String.IsNullOrEmpty(a.UENNo) ? false : a.UENNo.Contains(unitcode)
                                 //|| a.UnitCode == unitcode
                                 //a.UENNo.Contains(unitcode) || a.UnitCode == unitcode
                                 //a.UnitCode == unitcode || a.UENNo.Contains(unitcode)

                                 //&& a.ReceiptDate.AddHours(offset).Date >= DateFrom.Date
                                 && a.ReceiptDate.AddHours(offset).Date < DateFrom.Date
                                 select new
            {
                ReceiptDate = a.ReceiptDate,
                CodeRequirment = d.CodeRequirment,
                ProductCode = b.ProductCode,
                ProductName = b.ProductName,
                RO = b.RONo,
                Uom = b.UomUnit,
                Buyer = f.BuyerCode,
                PlanPo = b.POSerialNumber,
                NoArticle = f.Article,
                QtyReceipt = b.ReceiptQuantity,
                QtyCorrection = ty.POSerialNumber == null ? 0 : ty.Quantity,
                QtyExpend = ww.POSerialNumber == null ? 0 : ww.Quantity,
                PriceReceipt = b.PricePerDealUnit,
                PriceCorrection = ty.POSerialNumber == null ? 0 : ty.PricePerDealUnit,
                PriceExpend = ww.POSerialNumber == null ? 0 : ww.PricePerDealUnit,
                POId = b.POId,
                URNType = a.URNType,
                UnitCode = a.UnitCode,
                UENNo = a.UENNo,
                UnitSenderCode = dd.UnitSenderCode == null ? "-" : dd.UnitSenderCode,
                UnitRequestName = dd.UnitRequestName == null ? "-" : dd.UnitRequestName,
                ExpenditureTo = dd.ExpenditureTo == null ? "-" : dd.ExpenditureTo,
                a.IsDeleted
            });
            var CobaPP = from a in PPAwal
                         //where a.ReceiptDate.AddHours(offset).Date < DateFrom.Date && a.CodeRequirment == (String.IsNullOrWhiteSpace(ctg) ? a.CodeRequirment : ctg) && a.IsDeleted == false
                         where a.UENNo.Contains((String.IsNullOrWhiteSpace(unitcode) ? a.UnitCode : unitcode)) || a.UnitCode == (String.IsNullOrWhiteSpace(unitcode) ? a.UnitCode : unitcode)
                         select a;
            var PPAkhir = from a in dbContext.GarmentUnitReceiptNotes
                          join b in dbContext.GarmentUnitReceiptNoteItems on a.Id equals b.URNId
                          join d in dbContext.GarmentDeliveryOrderDetails on b.POId equals d.POId
                          join f in dbContext.GarmentInternalPurchaseOrders on b.POId equals f.Id
                          //join f in SaldoAwal on b.POId equals f.POID
                          join e in dbContext.GarmentReceiptCorrectionItems on b.Id equals e.URNItemId into RC
                          from ty in RC.DefaultIfEmpty()
                          join c in dbContext.GarmentUnitExpenditureNoteItems on b.UENItemId equals c.Id into UE
                          from ww in UE.DefaultIfEmpty()
                          join r in dbContext.GarmentUnitExpenditureNotes on ww.UENId equals r.Id into UEN
                          from dd in UEN.DefaultIfEmpty()
                          where d.CodeRequirment == (String.IsNullOrWhiteSpace(ctg) ? d.CodeRequirment : ctg) &&
                          a.IsDeleted == false && b.IsDeleted == false
                          //String.IsNullOrEmpty(a.UENNo) ? false : a.UENNo.Contains(unitcode)
                          //|| a.UnitCode == unitcode
                          //a.UnitCode == unitcode || a.UENNo.Contains(unitcode)
                          // a.UENNo.Contains(unitcode) || a.UnitCode == unitcode     /*String.IsNullOrEmpty(a.UENNo) ? true :*/
                          && a.ReceiptDate.AddHours(offset).Date >= DateFrom.Date &&
                          a.ReceiptDate.AddHours(offset).Date <= DateTo.Date

                          select new
            {
                ReceiptDate     = a.ReceiptDate,
                CodeRequirment  = d.CodeRequirment,
                ProductCode     = b.ProductCode,
                ProductName     = b.ProductName,
                RO              = b.RONo,
                Uom             = b.UomUnit,
                Buyer           = f.BuyerCode,
                PlanPo          = b.POSerialNumber,
                NoArticle       = f.Article,
                QtyReceipt      = b.ReceiptQuantity,
                QtyCorrection   = ty.POSerialNumber == null ? 0 : ty.Quantity,
                QtyExpend       = ww.POSerialNumber == null ? 0 : ww.Quantity,
                PriceReceipt    = b.PricePerDealUnit,
                PriceCorrection = ty.POSerialNumber == null ? 0 : ty.PricePerDealUnit,
                PriceExpend     = ww.POSerialNumber == null ? 0 : ww.PricePerDealUnit,
                POId            = b.POId,
                URNType         = a.URNType,
                UnitCode        = a.UnitCode,
                UENNo           = a.UENNo,
                UnitSenderCode  = dd.UnitSenderCode == null ? "-" : dd.UnitSenderCode,
                UnitRequestName = dd.UnitRequestName == null ? "-" : dd.UnitRequestName,
                ExpenditureTo   = dd.ExpenditureTo == null ? "-" : dd.ExpenditureTo,
                a.IsDeleted
            };
            var CobaPPAkhir = from a in PPAkhir
                              where a.UENNo.Contains((String.IsNullOrWhiteSpace(unitcode) ? a.UnitCode : unitcode)) || a.UnitCode == (String.IsNullOrWhiteSpace(unitcode) ? a.UnitCode : unitcode)
                              //where a.ReceiptDate.AddHours(offset).Date >= DateFrom.Date
                              //      && a.ReceiptDate.AddHours(offset).Date <= DateTo.Date
                              //      && a.CodeRequirment == (String.IsNullOrWhiteSpace(ctg) ? a.CodeRequirment : ctg)
                              //      && a.IsDeleted == false
                              select a;

            var SaldoAwal = from query in CobaPP
                            group query by new { query.ProductCode, query.ProductName, query.RO, query.PlanPo, query.POId, query.UnitCode, query.UnitSenderCode, query.UnitRequestName } into data
                select new AccountingStockReportViewModel
            {
                ProductCode            = data.Key.ProductCode,
                ProductName            = data.FirstOrDefault().ProductName,
                RO                     = data.Key.RO,
                Buyer                  = data.FirstOrDefault().Buyer,
                PlanPo                 = data.FirstOrDefault().PlanPo,
                NoArticle              = data.FirstOrDefault().NoArticle,
                BeginningBalanceQty    = data.Sum(x => x.QtyReceipt) + Convert.ToDecimal(data.Sum(x => x.QtyCorrection)) - Convert.ToDecimal(data.Sum(x => x.QtyExpend)),
                BeginningBalanceUom    = data.FirstOrDefault().Uom,
                BeginningBalancePrice  = data.Sum(x => x.PriceReceipt) + Convert.ToDecimal(data.Sum(x => x.PriceCorrection)) - Convert.ToDecimal(data.Sum(x => x.PriceExpend)),
                ReceiptCorrectionQty   = 0,
                ReceiptPurchaseQty     = 0,
                ReceiptProcessQty      = 0,
                ReceiptKon2AQty        = 0,
                ReceiptKon2BQty        = 0,
                ReceiptKon2CQty        = 0,
                ReceiptKon1MNSQty      = 0,
                ReceiptKon2DQty        = 0,
                ReceiptCorrectionPrice = 0,
                ReceiptPurchasePrice   = 0,
                ReceiptProcessPrice    = 0,
                ReceiptKon2APrice      = 0,
                ReceiptKon2BPrice      = 0,
                ReceiptKon2CPrice      = 0,
                ReceiptKon1MNSPrice    = 0,
                ReceiptKon2DPrice      = 0,
                ExpendReturQty         = 0,
                ExpendRestQty          = 0,
                ExpendProcessQty       = 0,
                ExpendSampleQty        = 0,
                ExpendKon2AQty         = 0,
                ExpendKon2BQty         = 0,
                ExpendKon2CQty         = 0,
                ExpendKon1MNSQty       = 0,
                ExpendKon2DQty         = 0,
                ExpendReturPrice       = 0,
                ExpendRestPrice        = 0,
                ExpendProcessPrice     = 0,
                ExpendSamplePrice      = 0,
                ExpendKon2APrice       = 0,
                ExpendKon2BPrice       = 0,
                ExpendKon2CPrice       = 0,
                ExpendKon1MNSPrice     = 0,
                ExpendKon2DPrice       = 0,
                EndingBalanceQty       = 0,
                EndingBalancePrice     = 0,
                POId                   = data.FirstOrDefault().POId
            };
            var SaldoAkhir = from query in CobaPPAkhir
                             group query by new { query.ProductCode, query.ProductName, query.RO, query.PlanPo, query.POId, query.UnitCode, query.UnitSenderCode, query.UnitRequestName } into data
                select new AccountingStockReportViewModel
            {
                ProductCode           = data.Key.ProductCode,
                ProductName           = data.Key.ProductName,
                RO                    = data.Key.RO,
                Buyer                 = data.FirstOrDefault().Buyer,
                PlanPo                = data.FirstOrDefault().PlanPo,
                NoArticle             = data.FirstOrDefault().NoArticle,
                BeginningBalanceQty   = /*data.Sum(x => x.QtyReceipt) + Convert.ToDecimal(data.Sum(x => x.QtyCorrection)) - Convert.ToDecimal(data.Sum(x => x.QtyExpend))*/ 0,
                BeginningBalanceUom   = data.FirstOrDefault().Uom,
                BeginningBalancePrice = /*data.Sum(x => x.PriceReceipt) + Convert.ToDecimal(data.Sum(x => x.PriceCorrection)) - Convert.ToDecimal(data.Sum(x => x.PriceExpend))*/ 0,
                ReceiptCorrectionQty  = 0,
                ReceiptPurchaseQty    = data.FirstOrDefault().URNType == "PEMBELIAN" && data.FirstOrDefault().UnitCode == unitcode?data.Sum(x => x.QtyReceipt) : 0,
                                            ReceiptProcessQty = data.FirstOrDefault().URNType == "PROSES" && data.FirstOrDefault().UnitCode == unitcode?data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptKon2AQty        = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2A" ? data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptKon2BQty        = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2B" ? data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptKon2CQty        = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2C" ? data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptKon1MNSQty      = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C1A" ? data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptKon2DQty        = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C1B" ? data.Sum(x => x.QtyReceipt) : 0,
                                                                    ReceiptCorrectionPrice = 0,
                                                                    ReceiptPurchasePrice   = data.FirstOrDefault().URNType == "PEMBELIAN" && data.FirstOrDefault().UnitCode == unitcode?data.Sum(x => x.PriceReceipt) : 0,
                                                                                                 ReceiptProcessPrice = data.FirstOrDefault().URNType == "PROSES" && data.FirstOrDefault().UnitCode == unitcode?data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ReceiptKon2APrice   = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2A" ? data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ReceiptKon2BPrice   = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2B" ? data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ReceiptKon2CPrice   = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C2C" ? data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ReceiptKon1MNSPrice = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C1A" ? data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ReceiptKon2DPrice   = data.FirstOrDefault().URNType == "GUDANG LAIN" && data.FirstOrDefault().UENNo.Substring(3, 3) == "C1B" ? data.Sum(x => x.PriceReceipt) : 0,
                                                                                                                           ExpendReturQty      = data.FirstOrDefault().ExpenditureTo == "EXTERNAL" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                     ExpendRestQty    = 0,
                                                                                                                                                     ExpendProcessQty = data.FirstOrDefault().ExpenditureTo == "PROSES" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                            ExpendSampleQty = data.FirstOrDefault().ExpenditureTo == "SAMPLE" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                  ExpendKon2AQty = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2A" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                                       ExpendKon2BQty = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2B" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                                                            ExpendKon2CQty = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2C" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                                                                                 ExpendKon1MNSQty = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 1A" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                                                                                                        ExpendKon2DQty = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 1B" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.QtyExpend) : 0,
                                                                                                                                                                                                                                                                                                             ExpendReturPrice = data.FirstOrDefault().ExpenditureTo == "EXTERNAL" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                    ExpendRestPrice    = 0,
                                                                                                                                                                                                                                                                                                                                    ExpendProcessPrice = data.FirstOrDefault().ExpenditureTo == "PROSES" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                             ExpendSamplePrice = data.FirstOrDefault().ExpenditureTo == "SAMPLE" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                     ExpendKon2APrice = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2A" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                                            ExpendKon2BPrice = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2B" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                                                                   ExpendKon2CPrice = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 2C" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                                                                                          ExpendKon1MNSPrice = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 1A" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   ExpendKon2DPrice = data.FirstOrDefault().ExpenditureTo == "GUDANG LAIN" && data.FirstOrDefault().UnitRequestName == "CENTRAL 1B" && data.FirstOrDefault().UnitSenderCode == unitcode?data.Sum(x => x.PriceExpend) : 0,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          EndingBalanceQty   = Convert.ToDecimal(Convert.ToDouble(data.Sum(x => x.QtyReceipt)) - data.Sum(x => x.QtyExpend)),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          EndingBalancePrice = Convert.ToDecimal(Convert.ToDouble(data.Sum(x => x.PriceReceipt)) - data.Sum(x => x.PriceExpend)),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          POId = data.FirstOrDefault().POId
            };

            List <AccountingStockReportViewModel> Data1 = SaldoAwal.Concat(SaldoAkhir).ToList();

            var Data = (from query in Data1
                        group query by new { query.POId, query.ProductCode, query.RO } into groupdata
                        select new AccountingStockReportViewModel
            {
                ProductCode = groupdata.FirstOrDefault().ProductCode == null ? "-" : groupdata.FirstOrDefault().ProductCode,
                ProductName = groupdata.FirstOrDefault().ProductName == null ? "-" : groupdata.FirstOrDefault().ProductName,
                RO = groupdata.FirstOrDefault().RO == null ? "-" : groupdata.FirstOrDefault().RO,
                Buyer = groupdata.FirstOrDefault().Buyer == null ? "-" : groupdata.FirstOrDefault().Buyer,
                PlanPo = groupdata.FirstOrDefault().PlanPo == null ? "-" : groupdata.FirstOrDefault().PlanPo,
                NoArticle = groupdata.FirstOrDefault().NoArticle == null ? "-" : groupdata.FirstOrDefault().NoArticle,
                BeginningBalanceQty = groupdata.Sum(x => x.BeginningBalanceQty),
                BeginningBalanceUom = groupdata.FirstOrDefault().BeginningBalanceUom,
                BeginningBalancePrice = groupdata.Sum(x => x.BeginningBalancePrice),
                ReceiptCorrectionQty = 0,
                ReceiptPurchaseQty = groupdata.Sum(x => x.ReceiptPurchaseQty),
                ReceiptProcessQty = groupdata.Sum(x => x.ReceiptProcessQty),
                ReceiptKon2AQty = groupdata.Sum(x => x.ReceiptKon2AQty),
                ReceiptKon2BQty = groupdata.Sum(x => x.ReceiptKon2BQty),
                ReceiptKon2CQty = groupdata.Sum(x => x.ReceiptKon2CQty),
                ReceiptKon1MNSQty = groupdata.Sum(x => x.ReceiptKon1MNSQty),
                ReceiptKon2DQty = groupdata.Sum(x => x.ReceiptKon2DQty),
                ReceiptCorrectionPrice = 0,
                ReceiptPurchasePrice = groupdata.Sum(x => x.ReceiptPurchasePrice),
                ReceiptProcessPrice = groupdata.Sum(x => x.ReceiptProcessPrice),
                ReceiptKon2APrice = groupdata.Sum(x => x.ReceiptKon2APrice),
                ReceiptKon2BPrice = groupdata.Sum(x => x.ReceiptKon2BPrice),
                ReceiptKon2CPrice = groupdata.Sum(x => x.ReceiptKon2CPrice),
                ReceiptKon1MNSPrice = groupdata.Sum(x => x.ReceiptKon1MNSPrice),
                ReceiptKon2DPrice = groupdata.Sum(x => x.ReceiptKon2DPrice),
                ExpendReturQty = groupdata.Sum(x => x.ExpendReturQty),
                ExpendRestQty = 0,
                ExpendProcessQty = groupdata.Sum(x => x.ExpendProcessQty),
                ExpendSampleQty = groupdata.Sum(x => x.ExpendSampleQty),
                ExpendKon2AQty = groupdata.Sum(x => x.ExpendKon2AQty),
                ExpendKon2BQty = groupdata.Sum(x => x.ExpendKon2BQty),
                ExpendKon2CQty = groupdata.Sum(x => x.ExpendKon2CQty),
                ExpendKon1MNSQty = groupdata.Sum(x => x.ExpendKon1MNSQty),
                ExpendKon2DQty = groupdata.Sum(x => x.ExpendKon2DQty),
                ExpendReturPrice = groupdata.Sum(x => x.ExpendReturPrice),
                ExpendRestPrice = 0,
                ExpendProcessPrice = groupdata.Sum(x => x.ExpendProcessPrice),
                ExpendSamplePrice = groupdata.Sum(x => x.ExpendSamplePrice),
                ExpendKon2APrice = groupdata.Sum(x => x.ExpendKon2APrice),
                ExpendKon2BPrice = groupdata.Sum(x => x.ExpendKon2BPrice),
                ExpendKon2CPrice = groupdata.Sum(x => x.ExpendKon2CPrice),
                ExpendKon1MNSPrice = groupdata.Sum(x => x.ExpendKon1MNSPrice),
                ExpendKon2DPrice = groupdata.Sum(x => x.ExpendKon2DPrice),
                EndingBalanceQty = Convert.ToDecimal((groupdata.Sum(x => x.BeginningBalanceQty) + groupdata.Sum(x => x.ReceiptPurchaseQty) + groupdata.Sum(x => x.ReceiptProcessQty) + groupdata.Sum(x => x.ReceiptKon2AQty) + groupdata.Sum(x => x.ReceiptKon2BQty) + groupdata.Sum(x => x.ReceiptKon2CQty) + groupdata.Sum(x => x.ReceiptKon1MNSQty) + groupdata.Sum(x => x.ReceiptKon2DQty) + 0) - (Convert.ToDecimal(groupdata.Sum(x => x.ExpendProcessQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendSampleQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2AQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2BQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2CQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon1MNSQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2DQty)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendReturPrice)))),
                EndingBalancePrice = Convert.ToDecimal((groupdata.Sum(x => x.BeginningBalancePrice) + groupdata.Sum(x => x.ReceiptPurchasePrice) + groupdata.Sum(x => x.ReceiptProcessPrice) + groupdata.Sum(x => x.ReceiptKon2APrice) + groupdata.Sum(x => x.ReceiptKon2BPrice) + groupdata.Sum(x => x.ReceiptKon2CPrice) + groupdata.Sum(x => x.ReceiptKon1MNSPrice) + groupdata.Sum(x => x.ReceiptKon2DPrice) + 0) - (Convert.ToDecimal(groupdata.Sum(x => x.ExpendReturPrice)) + 0 + Convert.ToDecimal(groupdata.Sum(x => x.ExpendProcessPrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendSamplePrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2APrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2BPrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2CPrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon1MNSPrice)) + Convert.ToDecimal(groupdata.Sum(x => x.ExpendKon2DPrice))))
            });


            return(Data.AsQueryable());
        }
Exemplo n.º 21
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            bool doPick = false;

            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            // Mouse and keyboard movement
            if (Keyboard.LeftRightAxis != 0 || Keyboard.UpDownAxis != 0)
            {
                _keys = true;
            }

            var curDamp = (float)System.Math.Exp(-Damping * DeltaTime);

            // Zoom & Roll
            if (Touch.TwoPoint)
            {
                if (!_twoTouchRepeated)
                {
                    _twoTouchRepeated = true;
                    _angleRollInit    = Touch.TwoPointAngle - _angleRoll;
                    _offsetInit       = Touch.TwoPointMidPoint - _offset;
                }
                _zoomVel   = Touch.TwoPointDistanceVel * -0.01f;
                _angleRoll = Touch.TwoPointAngle - _angleRollInit;
                _offset    = Touch.TwoPointMidPoint - _offsetInit;
            }
            else
            {
                _twoTouchRepeated = false;
                _zoomVel          = Mouse.WheelVel * -0.5f;
                _angleRoll       *= curDamp * 0.8f;
                _offset          *= curDamp * 0.8f;
            }

            // UpDown / LeftRight rotation
            if (Mouse.LeftButton)
            {
                _picker.PickPoint = Mouse.Position;
                doPick            = true;
                _keys             = false;
                _angleVelHorz     = -RotationSpeed * Mouse.XVel * 0.000002f;
                _angleVelVert     = -RotationSpeed * Mouse.YVel * 0.000002f;
            }
            else if (Touch.GetTouchActive(TouchPoints.Touchpoint_0) && !Touch.TwoPoint)
            {
                _keys             = false;
                _picker.PickPoint = Touch.GetPosition(TouchPoints.Touchpoint_0);
                doPick            = true;
                float2 touchVel;
                touchVel      = Touch.GetVelocity(TouchPoints.Touchpoint_0);
                _angleVelHorz = -RotationSpeed * touchVel.x * 0.000002f;
                _angleVelVert = -RotationSpeed * touchVel.y * 0.000002f;
            }
            else
            {
                if (_keys)
                {
                    _angleVelHorz = -RotationSpeed * Keyboard.LeftRightAxis * 0.002f;
                    _angleVelVert = -RotationSpeed * Keyboard.UpDownAxis * 0.002f;
                }
                else
                {
                    _angleVelHorz *= curDamp;
                    _angleVelVert *= curDamp;
                }
            }

            float wuggyYawSpeed = Keyboard.WSAxis * Keyboard.ADAxis * 0.03f;
            float wuggySpeed    = Keyboard.WSAxis * -10;

            // Wuggy XForm
            float wuggyYaw = _wuggyTransform.Rotation.y;

            wuggyYaw += wuggyYawSpeed;
            wuggyYaw  = NormRot(wuggyYaw);
            float3 wuggyPos = _wuggyTransform.Translation;

            wuggyPos += new float3((float)Sin(wuggyYaw), 0, (float)Cos(wuggyYaw)) * wuggySpeed;
            _wuggyTransform.Rotation    = new float3(0, wuggyYaw, 0);
            _wuggyTransform.Translation = wuggyPos;

            // Wuggy Wheels
            _wgyWheelBigR.Rotation  += new float3(wuggySpeed * 0.008f, 0, 0);
            _wgyWheelBigL.Rotation  += new float3(wuggySpeed * 0.008f, 0, 0);
            _wgyWheelSmallR.Rotation = new float3(_wgyWheelSmallR.Rotation.x + wuggySpeed * 0.016f, -Keyboard.ADAxis * 0.3f, 0);
            _wgyWheelSmallL.Rotation = new float3(_wgyWheelSmallR.Rotation.x + wuggySpeed * 0.016f, -Keyboard.ADAxis * 0.3f, 0);

            // SCRATCH:
            // _guiSubText.Text = target.Name + " " + target.GetComponent<TargetComponent>().ExtraInfo;
            SceneNodeContainer target = GetClosest();
            float camYaw = 0;

            if (target != null)
            {
                float3 delta = target.GetTransform().Translation - _wuggyTransform.Translation;
                camYaw = (float)Atan2(-delta.x, -delta.z) - _wuggyTransform.Rotation.y;
            }

            camYaw = NormRot(camYaw);
            float deltaAngle = camYaw - _wgyNeckHi.Rotation.y;

            if (deltaAngle > M.Pi)
            {
                deltaAngle = deltaAngle - M.TwoPi;
            }
            if (deltaAngle < -M.Pi)
            {
                deltaAngle = deltaAngle + M.TwoPi;
            }
            ;
            var newYaw = _wgyNeckHi.Rotation.y + (float)M.Clamp(deltaAngle, -0.06, 0.06);

            newYaw = NormRot(newYaw);
            _wgyNeckHi.Rotation = new float3(0, newYaw, 0);


            _zoom += _zoomVel;
            // Limit zoom
            if (_zoom < 80)
            {
                _zoom = 80;
            }
            if (_zoom > 2000)
            {
                _zoom = 2000;
            }

            _angleHorz += _angleVelHorz;
            // Wrap-around to keep _angleHorz between -PI and + PI
            _angleHorz = M.MinAngle(_angleHorz);

            _angleVert += _angleVelVert;
            // Limit pitch to the range between [-PI/2, + PI/2]
            _angleVert = M.Clamp(_angleVert, -M.PiOver2, M.PiOver2);

            // Wrap-around to keep _angleRoll between -PI and + PI
            _angleRoll = M.MinAngle(_angleRoll);


            // Create the camera matrix and set it as the current ModelView transformation
            var mtxRot = float4x4.CreateRotationZ(_angleRoll) * float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);
            var mtxCam = float4x4.LookAt(0, 20, -_zoom, 0, 0, 0, 0, 1, 0);

            _renderer.View = mtxCam * mtxRot * _sceneScale;
            var mtxOffset = float4x4.CreateTranslation(2 * _offset.x / Width, -2 * _offset.y / Height, 0);

            RC.Projection = mtxOffset * _projection;


            _renderer.Traverse(_scene.Children);
            _renderer.Traverse(_screen.Children);
            if (doPick)
            {
                _picker.VP = RC.Projection * _renderer.View;
                _picker.Traverse(_screen.Children);
                string touchedOb = _picker.PickResults?.OrderBy(pr => pr.PickPntClip.z).FirstOrDefault()?.Node?.Name;
                if (!string.IsNullOrEmpty(touchedOb))
                {
                    Diagnostics.Log(touchedOb);
                }
            }


            // Swap buffers: Show the contents of the backbuffer (containing the currently rerndered farame) on the front buffer.
            Present();
        }
Exemplo n.º 22
0
 // <p style='font-style:italic;'>Since 1.0.28 (Release 8.4)</p><p>Returns list of posts.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>Glip</td><td>Availability of Glip</td></tr></tbody></table><h4>API Group</h4><p>Light</p>
 public Task <GlipPosts> List()
 {
     return(RC.Get <GlipPosts>(Endpoint(false), null));
 }
Exemplo n.º 23
0
 // <p style='font-style:italic;'>Since 1.0.28 (Release 8.4)</p><p>Returns list of posts.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>Glip</td><td>Availability of Glip</td></tr></tbody></table><h4>API Group</h4><p>Light</p>
 public Task <GlipPosts> List(object parameters)
 {
     return(RC.Get <GlipPosts>(Endpoint(false), parameters));
 }
Exemplo n.º 24
0
        private static void Save(IResource res, Stream stream, ImageFileFormat fmt)
        {
            var texture     = res.Resource as Texture2D;
            var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
            {
                Width             = (int)texture.Description.Width,
                Height            = (int)texture.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = texture.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            RC.CopyResource(res, textureCopy);

            DataStream dataStream;
            var        dataBox = RC.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                MapFlags.None,
                out dataStream);

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };

            var bitmap = new Bitmap(
                MyRender11.WIC,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
                dataRectangle);

            using (var wicStream = new WICStream(MyRender11.WIC, stream))
            {
                BitmapEncoder bitmapEncoder;
                switch (fmt)
                {
                case ImageFileFormat.Png:
                    bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Jpg:
                    bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                case ImageFileFormat.Bmp:
                    bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
                    break;

                default:
                    MyRenderProxy.Assert(false, "Unsupported file format.");
                    bitmapEncoder = null;
                    break;
                }
                if (bitmapEncoder != null)
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                    bitmapEncoder.Dispose();
                }
            }

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
Exemplo n.º 25
0
 // Synchronizes messages.
 public Task <GetMessageSyncResponse> List(object parameters)
 {
     return(RC.Get <GetMessageSyncResponse>(Endpoint(false), parameters));
 }
Exemplo n.º 26
0
 // Synchronizes messages.
 public Task <GetMessageSyncResponse> List()
 {
     return(RC.Get <GetMessageSyncResponse>(Endpoint(false), null));
 }
Exemplo n.º 27
0
		public static string SectionToString(RC.PackageSection section) {
			IntPtr raw_ret = rc_package_section_to_string((int) section);
			string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
			return ret;
		}
Exemplo n.º 28
0
Arquivo: SysEx.cs Projeto: BclEx/GpuEx
 internal static void LOG(RC rc, string format, params object[] args)
 {
     Console.WriteLine("l:" + string.Format(format, args));
 }
Exemplo n.º 29
0
 //--- Constructors ---
 public DigestLookupEntry(DateTime timestamp, int index, RC type) {
     this.Timestamp = timestamp;
     this.Index = index;
     this.Type = type;
 }
 // Returns current API version(s) and server info.
 public Task <GetVersionsResponse> Get()
 {
     return(RC.Get <GetVersionsResponse>(Endpoint(true), null));
 }
Exemplo n.º 31
0
 // Get Phone Number by ID
 public Task <PhoneNumberInfo> Get()
 {
     return(RC.Get <PhoneNumberInfo>(Endpoint(true), null));
 }
Exemplo n.º 32
0
        /// <param name="clearColor">Color used to clear render targets. Defaults to black</param>
        internal static void Run(IRtvBindable renderTarget, IRtvTexture intermediate, ISrvBindable initialResourceView,
                                 int maxOffset = 5, MyBlurDensityFunctionType densityFunctionType = MyBlurDensityFunctionType.Gaussian, float WeightParameter = 1.5f,
                                 IDepthStencilState depthStencilState = null, int stencilRef      = 0x0, Color4 clearColor = default(Color4),
                                 float depthDiscardThreshold          = 0.0f, MyViewport?viewport = null)
        {
            ProfilerShort.Begin("MyBlur.Run");
            MyGpuProfiler.IC_BeginBlock("MyBlur.Run");
            Debug.Assert(initialResourceView != null);
            Debug.Assert(intermediate != null);
            Debug.Assert(renderTarget != null);

            int shaderKey = InitShaders(densityFunctionType, maxOffset, depthDiscardThreshold);

            RC.PixelShader.SetConstantBuffer(5, m_blurConstantBuffer);

            BlurConstants constants = new BlurConstants
            {
                DistributionWeight = WeightParameter,
                StencilRef         = stencilRef,
            };
            var mapping = MyMapping.MapDiscard(m_blurConstantBuffer);

            mapping.WriteAndPosition(ref constants);
            mapping.Unmap();

            // Horizontal pass
            // NOTE: DepthStencilState is not used here because the resulted target
            // would not be usable to perform vertical pass. DepthStencil is stil
            // bindinded as SRV since it is sampled in the shader
            RC.ClearRtv(intermediate, clearColor);
            RC.SetRtv(intermediate);
            RC.PixelShader.SetSrv(0, MyGBuffer.Main.DepthStencil.SrvDepth);
            RC.PixelShader.SetSrv(4, MyGBuffer.Main.DepthStencil.SrvStencil);
            RC.SetDepthStencilState(MyDepthStencilStateManager.IgnoreDepthStencil);
            RC.PixelShader.SetSrv(5, initialResourceView);
            RC.PixelShader.Set(m_blurShaders[shaderKey].Item1);
            MyScreenPass.DrawFullscreenQuad(viewport);
            RC.PixelShader.SetSrv(5, null);

            // Vertical pass
            RC.ClearRtv(renderTarget, clearColor);
            if (depthStencilState == null)
            {
                RC.SetRtv(renderTarget);
            }
            else
            {
                RC.SetDepthStencilState(depthStencilState, stencilRef);
                RC.SetRtv(MyGBuffer.Main.DepthStencil, MyDepthStencilAccess.ReadOnly, renderTarget);
            }

            RC.PixelShader.SetSrv(5, intermediate);
            RC.PixelShader.Set(m_blurShaders[shaderKey].Item2);
            MyScreenPass.DrawFullscreenQuad(viewport);

            RC.PixelShader.SetSrv(0, null);
            RC.PixelShader.SetSrv(4, null);
            RC.PixelShader.SetSrv(5, null);
            RC.SetRtv(null);

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();
        }
Exemplo n.º 33
0
        internal unsafe override sealed void RecordCommands(MyRenderableProxy proxy)
        {
            if (proxy.Mesh.Buffers.IB == IndexBufferId.NULL || proxy.Draw.IndexCount == 0)
            {
                return;
            }


            Stats.Meshes++;

            SetProxyConstants(proxy);
            BindProxyGeometry(proxy);

            Debug.Assert(proxy.DepthShaders.VS != null);

            RC.BindShaders(proxy.DepthShaders);

            if ((proxy.flags & MyRenderableProxyFlags.DisableFaceCulling) > 0)
            {
                RC.SetRS(MyRender11.m_nocullRasterizerState);
            }
            else
            {
                RC.SetRS(DefaultRasterizer);
            }


            //for (int i = 0; i < proxy.depthOnlySubmeshes.Length; i++)
            //{
            //    Stats.Submeshes++;

            //    var submesh = proxy.depthOnlySubmeshes[i];

            var submesh = proxy.Draw;

            if (submesh.MaterialId != Locals.matTexturesID && (!((proxy.flags & MyRenderableProxyFlags.DepthSkipTextures) > 0)))
            {
                Locals.matTexturesID = submesh.MaterialId;
                var material = MyMaterials1.ProxyPool.Data[submesh.MaterialId.Index];
                RC.MoveConstants(ref material.MaterialConstants);
                RC.SetConstants(ref material.MaterialConstants, MyCommon.MATERIAL_SLOT);
                RC.SetSRVs(ref material.MaterialSRVs);
            }

            if (proxy.skinningMatrices != null)
            {
                Stats.ObjectConstantsChanges++;

                MyObjectData objectData = proxy.ObjectData;
                //objectData.Translate(-MyEnvironment.CameraPosition);

                MyMapping mapping;
                mapping = MyMapping.MapDiscard(RC.Context, proxy.objectBuffer);
                void *ptr = &objectData;
                mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData));

                if (proxy.skinningMatrices != null)
                {
                    if (submesh.BonesMapping == null)
                    {
                        for (int j = 0; j < Math.Min(MyRender11Constants.SHADER_MAX_BONES, proxy.skinningMatrices.Length); j++)
                        {
                            mapping.stream.Write(Matrix.Transpose(proxy.skinningMatrices[j]));
                        }
                    }
                    else
                    {
                        for (int j = 0; j < submesh.BonesMapping.Length; j++)
                        {
                            mapping.stream.Write(Matrix.Transpose(proxy.skinningMatrices[submesh.BonesMapping[j]]));
                        }
                    }
                }

                mapping.Unmap();
            }

            if (proxy.instanceCount == 0)
            {
                RC.Context.DrawIndexed(submesh.IndexCount, submesh.StartIndex, submesh.BaseVertex);
                RC.Stats.DrawIndexed++;
                Stats.Instances++;
                Stats.Triangles += submesh.IndexCount / 3;
            }
            else
            {
                RC.Context.DrawIndexedInstanced(submesh.IndexCount, proxy.instanceCount, submesh.StartIndex, submesh.BaseVertex, proxy.startInstance);
                RC.Stats.DrawIndexedInstanced++;
                Stats.Instances += proxy.instanceCount;
                Stats.Triangles += proxy.instanceCount * submesh.IndexCount / 3;
            }
            //}
        }
Exemplo n.º 34
0
        static void ptrmapPut(BtShared bt, Pid key, PTRMAP type, Pid parent, ref RC rcRef)
        {
            if (rcRef != RC.OK) return;

            Debug.Assert(MutexEx.Held(bt.Mutex));
            // The master-journal page number must never be used as a pointer map page
            Debug.Assert(!PTRMAP_ISPAGE(bt, PENDING_BYTE_PAGE(bt)));

            Debug.Assert(bt.AutoVacuum);
            if (key == 0)
            {
                rcRef = SysEx.CORRUPT_BKPT();
                return;
            }
            var ptrmapIdx = PTRMAP_PAGENO(bt, key); // The pointer map page number
            var page = (IPage)new PgHdr(); // The pointer map page
            var rc = bt.Pager.Acquire(ptrmapIdx, ref page, false);
            if (rc != RC.OK)
            {
                rcRef = rc;
                return;
            }
            var offset = (int)PTRMAP_PTROFFSET(ptrmapIdx, key); // Offset in pointer map page
            if (offset < 0)
            {
                rcRef = SysEx.CORRUPT_BKPT();
                goto ptrmap_exit;
            }
            Debug.Assert(offset <= (int)bt.UsableSize - 5);
            var ptrmap = Pager.GetData(page); // The pointer map page

            if (type != (PTRMAP)ptrmap[offset] || ConvertEx.Get4(ptrmap, offset + 1) != parent)
            {
                TRACE("PTRMAP_UPDATE: %d->(%d,%d)\n", key, type, parent);
                rcRef = rc = Pager.Write(page);
                if (rc == RC.OK)
                {
                    ptrmap[offset] = (byte)type;
                    ConvertEx.Put4(ptrmap, offset + 1, parent);
                }
            }

        ptrmap_exit:
            Pager.Unref(page);
        }
 // <p style='font-style:italic;'>Since 1.0.31 (Release 9.2)</p><p>Returns the list of users requested.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadAccounts</td><td>Viewing user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>API Group</h4><p>Medium</p>
 public Task <GetUserListResponse> Get(object parameters)
 {
     return(RC.Get <GetUserListResponse>(Endpoint(true), parameters));
 }
Exemplo n.º 36
0
		public bool Equal(RC.PackageMatch match2) {
			bool raw_ret = rc_package_match_equal(Handle, match2 == null ? IntPtr.Zero : match2.Handle);
			bool ret = raw_ret;
			return ret;
		}
Exemplo n.º 37
0
        // Init is called on startup.
        public override void Init()
        {
            var fontLato = AssetStorage.Get <Font>("Lato-Black.ttf");
            var vladimir = AssetStorage.Get <Font>("VLADIMIR.TTF");
            var gnuSerif = AssetStorage.Get <Font>("GNU-FreeSerif.ttf");

            _text = "FUSEE ThreeDFont Example";

            _threeDFontHelper = new ThreeDFontHelper(_text, fontLato);
            var outlinesLato = _threeDFontHelper.GetTextOutlinesWAngle(20);
            var geomLato     = new Jometri.Geometry(outlinesLato);

            geomLato.Extrude2DPolygon(2000, false);
            geomLato.Triangulate();
            _textMeshLato = new JometriMesh(geomLato);


            _threeDFontHelper = new ThreeDFontHelper(_text, vladimir);
            var outlinesVlad = _threeDFontHelper.GetTextOutlinesWAngle(7);
            var geomVlad     = new Jometri.Geometry(outlinesVlad);

            geomVlad.Extrude2DPolygon(200, false);
            geomVlad.Triangulate();
            _textMeshVlad = new JometriMesh(geomVlad);


            _threeDFontHelper = new ThreeDFontHelper(_text, gnuSerif);
            var outlinesGnu = _threeDFontHelper.GetTextOutlinesWAngle(40);
            var geomGnu     = new Jometri.Geometry(outlinesGnu);

            //geomVlad.Extrude2DPolygon(200, false);
            geomGnu.Triangulate();
            _textMeshGnu = new JometriMesh(geomGnu);

            ////////////////// Fill SceneNodeContainer ////////////////////////////////
            var parentNode = new SceneNodeContainer
            {
                Components = new List <SceneComponentContainer>(),
                Children   = new ChildList()
            };

            var parentTrans = new TransformComponent
            {
                Rotation    = float3.Zero,
                Scale       = new float3(0.01f, 0.01f, 0.01f),
                Translation = new float3(0, 0, 10)
            };

            parentNode.Components.Add(parentTrans);


            //Vladimir
            var sceneNodeCVlad = new SceneNodeContainer {
                Components = new List <SceneComponentContainer>()
            };

            var meshCVlad = new Mesh
            {
                Vertices  = _textMeshVlad.Vertices,
                Triangles = _textMeshVlad.Triangles,
                Normals   = _textMeshVlad.Normals,
            };

            var tranCVlad = new TransformComponent
            {
                Rotation    = float3.Zero,
                Scale       = float3.One,
                Translation = new float3(0, 2000, 0)
            };

            sceneNodeCVlad.Components.Add(tranCVlad);
            sceneNodeCVlad.Components.Add(meshCVlad);

            //Lato
            var sceneNodeCLato = new SceneNodeContainer {
                Components = new List <SceneComponentContainer>()
            };

            var meshCLato = new Mesh
            {
                Vertices  = _textMeshLato.Vertices,
                Triangles = _textMeshLato.Triangles,
                Normals   = _textMeshLato.Normals,
            };
            var tranCLato = new TransformComponent
            {
                Rotation    = float3.Zero,
                Scale       = float3.One,
                Translation = new float3(0, 0, 0)
            };

            sceneNodeCLato.Components.Add(tranCLato);
            sceneNodeCLato.Components.Add(meshCLato);

            //GNU
            var sceneNodeCGnu = new SceneNodeContainer {
                Components = new List <SceneComponentContainer>()
            };

            var meshCGnu = new Mesh
            {
                Vertices  = _textMeshGnu.Vertices,
                Triangles = _textMeshGnu.Triangles,
                Normals   = _textMeshGnu.Normals,
            };
            var tranCGnu = new TransformComponent
            {
                Rotation    = float3.Zero,
                Scale       = float3.One,
                Translation = new float3(0, -2000, 0)
            };

            sceneNodeCGnu.Components.Add(tranCGnu);
            sceneNodeCGnu.Components.Add(meshCGnu);

            parentNode.Children.Add(sceneNodeCVlad);
            parentNode.Children.Add(sceneNodeCLato);
            parentNode.Children.Add(sceneNodeCGnu);

            var sc = new SceneContainer {
                Children = new List <SceneNodeContainer> {
                    parentNode
                }
            };

            var projComp = new ProjectionComponent(ProjectionMethod.PERSPECTIVE, 1, 5000, M.PiOver4);

            AddResizeDelegate(delegate { projComp.Resize(Width, Height); });
            sc.Children[0].Components.Insert(0, projComp);

            _renderer = new SceneRenderer(sc);

            var shaderFx = new ShaderEffect(new[] {
                new EffectPassDeclaration
                {
                    PS       = AssetStorage.Get <string>("FragShader.frag"),
                    VS       = AssetStorage.Get <string>("VertShader.vert"),
                    StateSet = new RenderStateSet
                    {
                        ZEnable = true
                    }
                }
            },
                                            new List <EffectParameterDeclaration>
            {
                new EffectParameterDeclaration {
                    Name = "xform", Value = float4x4.Identity
                }
            });

            RC.SetShaderEffect(shaderFx);

            // Set the clear color for the backbuffer
            RC.ClearColor = new float4(0, 0.61f, 0.88f, 1);
        }
Exemplo n.º 38
0
 static bool IsFatalError(RC rc)
 {
     return (rc != RC.OK && rc != RC.BUSY && C._ALWAYS(rc != RC.LOCKED));
 }
Exemplo n.º 39
0
 static void freePage(MemPage page, ref RC rc)
 {
     if ((rc) == RC.OK)
         rc = freePage2(page.Bt, page, page.ID);
 }
Exemplo n.º 40
0
Arquivo: SysEx.cs Projeto: BclEx/GpuEx
 internal static void LOG(RC rc, string x, params object[] args)
 {
 }
 // Create Post
 public Task <GlipPostInfo> Post()
 {
     return(RC.Post <GlipPostInfo>(Endpoint(true), null));
 }
Exemplo n.º 42
0
        static void insertCell(MemPage page, uint i, byte[] cell, ushort size, byte[] temp, Pid childID, ref RC rcRef)
        {
            if (rcRef != RC.OK) return;

            Debug.Assert(i <= page.Cells + page.Overflows);
            Debug.Assert(page.Cells <= MX_CELL(page.Bt) && MX_CELL(page.Bt) <= 10921);
            Debug.Assert(page.Overflows <= page.Ovfls.Length);
            Debug.Assert(MutexEx.Held(page.Bt.Mutex));
            // The cell should normally be sized correctly.  However, when moving a malformed cell from a leaf page to an interior page, if the cell size
            // wanted to be less than 4 but got rounded up to 4 on the leaf, then size might be less than 8 (leaf-size + pointer) on the interior node.  Hence
            // the term after the || in the following assert().
            Debug.Assert(size == cellSizePtr(page, cell) || (size == 8 && childID > 0));
            int skip = (childID != 0 ? 4 : 0);
            if (page.Overflows != 0 || size + 2 > page.Frees)
            {
                if (temp != null)
                {
                    Buffer.BlockCopy(cell, skip, temp, skip, size - skip);
                    cell = temp;
                }
                if (childID != 0)
                    ConvertEx.Put4(cell, childID);
                int j = page.Overflows++;
                Debug.Assert(j < page.Ovfls.Length);
                page.Ovfls[j].Cell = cell;
                page.OvflIdxs[j] = (ushort)i;
            }
            else
            {
                RC rc = Pager.Write(page.DBPage);
                if (rc != RC.OK)
                {
                    rcRef = rc;
                    return;
                }
                Debug.Assert(Pager.Iswriteable(page.DBPage));
                var data = page.Data; // The content of the whole page
                uint cellOffset = page.CellOffset; // Address of first cell pointer in data[]
                uint end = cellOffset + 2U * page.Cells; // First byte past the last cell pointer in data[]
                uint ins = cellOffset + 2U * i; // Index in data[] where new cell pointer is inserted
                uint idx = 0; // Where to write new cell content in data[]
                rc = allocateSpace(page, size, ref idx);
                if (rc != RC.OK) { rcRef = rc; return; }
                // The allocateSpace() routine guarantees the following two properties if it returns success
                Debug.Assert(idx >= end + 2);
                Debug.Assert(idx + size <= (int)page.Bt.UsableSize);
                page.Cells++;
                page.Frees -= (ushort)(2 + size);
                Buffer.BlockCopy(cell, skip, data, (int)(idx + skip), size - skip);
                if (childID != 0)
                    ConvertEx.Put4(data, idx, childID);
                {
                    //uint8 *ptr = &data[end]; // Used for moving information around in data[]
                    //uint8 *endPtr = &data[ins]; // End of the loop
                    //_assert((PTR_TO_INT(ptr) & 1) == 0); // ptr is always 2-byte aligned
                    //while (ptr > endPtr)
                    //{
                    //    *(uint16*)ptr = *(uint16*)&ptr[-2];
                    //    ptr -= 2;
                    //}
                    for (uint j = end; j > ins; j -= 2)
                    {
                        data[j + 0] = data[j - 2];
                        data[j + 1] = data[j - 1];
                    }
                }
                ConvertEx.Put2(data, ins, idx);
                ConvertEx.Put2(data, page.HdrOffset + 3, page.Cells);
#if !OMIT_AUTOVACUUM
                if (page.Bt.AutoVacuum)
                {
                    // The cell may contain a pointer to an overflow page. If so, write the entry for the overflow page into the pointer map.
                    ptrmapPutOvflPtr(page, cell, ref rcRef);
                }
#endif
            }
        }
Exemplo n.º 43
0
        public RC Rollback(RC tripCode)
        {
            var bt = Bt;

            Enter();
            RC rc;
            if (tripCode == RC.OK)
                rc = tripCode = saveAllCursors(bt, 0, null);
            else
                rc = RC.OK;
            if (tripCode != RC.OK)
                TripAllCursors(tripCode);

            btreeIntegrity(this);

            if (InTrans == TRANS.WRITE)
            {
                Debug.Assert(bt.InTransaction == TRANS.WRITE);
                var rc2 = bt.Pager.Rollback();
                if (rc2 != RC.OK)
                    rc = rc2;

                // The rollback may have destroyed the pPage1->aData value. So call btreeGetPage() on page 1 again to make
                // sure pPage1->aData is set correctly.
                MemPage page1 = new MemPage();
                if (btreeGetPage(bt, 1, ref page1, false) == RC.OK)
                {
                    Pid pages = ConvertEx.Get4(page1.Data, 28);
                    if (pages == 0) bt.Pager.Pages(out pages);
                    bt.Pages = pages;
                    releasePage(page1);
                }
                Debug.Assert(countWriteCursors(bt) == 0);
                bt.InTransaction = TRANS.READ;
            }

            btreeEndTransaction(this);
            Leave();
            return rc;
        }
 // Create Post
 public Task <GlipPostInfo> Post(object parameters)
 {
     return(RC.Post <GlipPostInfo>(Endpoint(true), parameters));
 }
Exemplo n.º 45
0
        static void dropCell(MemPage page, uint idx, ushort size, ref RC rcRef)
        {
            if (rcRef != RC.OK) return;

            Debug.Assert(idx < page.Cells);
            Debug.Assert(size == cellSize(page, idx));
            Debug.Assert(Pager.Iswriteable(page.DBPage));
            Debug.Assert(MutexEx.Held(page.Bt.Mutex));
            var data = page.Data;
            var ptr = page.CellOffset + 2 * idx; // Used to move bytes around within data[]
            var pc = (uint)ConvertEx.Get2(data, ptr); // Offset to cell content of cell being deleted
            var hdr = page.HdrOffset; // Beginning of the header.  0 most pages.  100 page 1
            ASSERTCOVERAGE(pc == ConvertEx.Get2(data, hdr + 5));
            ASSERTCOVERAGE(pc + size == page.Bt.UsableSize);
            if (pc < (uint)ConvertEx.Get2(data, hdr + 5) || pc + size > page.Bt.UsableSize)
            {
                rcRef = SysEx.CORRUPT_BKPT();
                return;
            }
            var rc = freeSpace(page, pc, size);
            if (rc != RC.OK)
            {
                rcRef = rc;
                return;
            }
            {
                //uint8* endPtr = &page->CellIdx[2 * page->Cells - 2]; // End of loop
                //_assert((PTR_TO_INT(ptr) & 1) == 0); // ptr is always 2-byte aligned
                //while (ptr < endPtr)
                //{
                //    *(uint16*)ptr = *(uint16*)&ptr[2];
                //    ptr += 2;
                //}
                Buffer.BlockCopy(data, (int)ptr + 2, data, (int)ptr, (int)(page.Cells - 1 - idx) * 2);
            }
            page.Cells--;
            // ConvertEx.Put2(&data[hdr + 3], page->Cells);
            data[page.HdrOffset + 3] = (byte)(page.Cells >> 8);
            data[page.HdrOffset + 4] = (byte)(page.Cells);
            page.Frees += 2;
        }
Exemplo n.º 46
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            // Mouse and keyboard movement
            if (Input.Keyboard.LeftRightAxis != 0 || Input.Keyboard.UpDownAxis != 0)
            {
                _keys = true;
            }

            if (Input.Mouse.LeftButton)
            {
                _pick         = true;
                _pickPos      = Input.Mouse.Position;
                _keys         = false;
                _angleVelHorz = -RotationSpeed * Input.Mouse.XVel * Time.DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * Input.Mouse.YVel * Time.DeltaTime * 0.0005f;
            }
            else if (Input.Touch.GetTouchActive(TouchPoints.Touchpoint_0))
            {
                _pick    = true;
                _pickPos = Input.Touch.GetPosition(TouchPoints.Touchpoint_0);
                var touchVel = Input.Touch.GetVelocity(TouchPoints.Touchpoint_0);
                _angleVelHorz = -RotationSpeed * touchVel.x * Time.DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * touchVel.y * Time.DeltaTime * 0.0005f;
            }
            else
            {
                _pick = false;
                if (_keys)
                {
                    _angleVelHorz = -RotationSpeed * Input.Keyboard.LeftRightAxis * Time.DeltaTime;
                    _angleVelVert = -RotationSpeed * Input.Keyboard.UpDownAxis * Time.DeltaTime;
                }
                else
                {
                    var curDamp = (float)System.Math.Exp(-Damping * Time.DeltaTime);
                    _angleVelHorz *= curDamp;
                    _angleVelVert *= curDamp;
                }
            }

            _angleHorz += _angleVelHorz;
            _angleVert += _angleVelVert;

            // Create the camera matrix and set it as the current ModelView transformation
            var mtxRot = float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);
            var mtxCam = float4x4.LookAt(0, 20, -600, 0, 150, 0, 0, 1, 0);

            // Check
            if (_pick)
            {
                Diagnostics.Log(_pickPos);
                float2 pickPosClip = _pickPos * new float2(2.0f / Width, -2.0f / Height) + new float2(-1, 1);

                _scenePicker.View = mtxCam * mtxRot;

                PickResult newPick = _scenePicker.Pick(pickPosClip).ToList().OrderBy(pr => pr.ClipPos.z).FirstOrDefault();

#if WEBBUILD
                if (newPick?.Node != _currentPick?.Node)
                {
                    if (_currentPick != null)
                    {
                        var ef = _currentPick.Node.GetComponent <ShaderEffectComponent>().Effect;
                        ef.SetEffectParam("DiffuseColor", _oldColor);
                    }
                    if (newPick != null)
                    {
                        var ef = newPick.Node.GetComponent <ShaderEffectComponent>().Effect;
                        _oldColor = (float4)ef.GetEffectParam("DiffuseColor"); // cast needed
                        ef.SetEffectParam("DiffuseColor", ColorUint.Tofloat4(ColorUint.LawnGreen));
                    }
                    _currentPick = newPick;
                }
#else
                if (newPick?.Node != _currentPick?.Node)
                {
                    dynamic shaderEffectComponent; // this needs to be dynamic! & reference Microsoft.CSharp.dll

                    if (_currentPick != null)
                    {
                        shaderEffectComponent = _currentPick.Node.GetComponent <ShaderEffectComponent>().Effect;
                        shaderEffectComponent.DiffuseColor = _oldColor;
                    }
                    if (newPick != null)
                    {
                        shaderEffectComponent = newPick.Node.GetComponent <ShaderEffectComponent>().Effect;
                        _oldColor             = (float4)shaderEffectComponent.DiffuseColor;
                        shaderEffectComponent.DiffuseColor = ColorUint.Tofloat4(ColorUint.LawnGreen);
                    }
                    _currentPick = newPick;
                }
#endif
                _pick = false;
            }

            RC.View = mtxCam * mtxRot;
            // Render the scene loaded in Init()
            _sceneRenderer.Render(RC);
#if GUI_SIMPLE
            //Set the view matrix for the interaction handler.
            _sih.View = RC.View;

            // Constantly check for interactive objects.
            if (!Input.Mouse.Desc.Contains("Android"))
            {
                _sih.CheckForInteractiveObjects(Input.Mouse.Position, Width, Height);
            }

            if (Input.Touch.GetTouchActive(TouchPoints.Touchpoint_0) && !Input.Touch.TwoPoint)
            {
                _sih.CheckForInteractiveObjects(Input.Touch.GetPosition(TouchPoints.Touchpoint_0), Width, Height);
            }
            _guiRenderer.Render(RC);
#endif
            // Swap buffers: Show the contents of the backbuffer (containing the currently rerndered farame) on the front buffer.
            Present();
        }
Exemplo n.º 47
0
        static void copyNodeContent(MemPage from, MemPage to, ref RC rcRef)
        {
            if (rcRef == RC.OK)
            {
                BtShared bt = from.Bt;
                var fromData = from.Data;
                var toData = to.Data;
                int fromHdr = from.HdrOffset;
                int toHdr = (to.ID == 1 ? 100 : 0);

                Debug.Assert(from.IsInit);
                Debug.Assert(from.Frees >= toHdr);
                Debug.Assert(ConvertEx.Get2(fromData, fromHdr + 5) <= (int)bt.UsableSize);

                // Copy the b-tree node content from page pFrom to page pTo.
                int data = ConvertEx.Get2(fromData, fromHdr + 5);
                Buffer.BlockCopy(fromData, data, toData, data, (int)bt.UsableSize - data);
                Buffer.BlockCopy(fromData, fromHdr, toData, toHdr, from.CellOffset + 2 * from.Cells);

                // Reinitialize page pTo so that the contents of the MemPage structure match the new data. The initialization of pTo can actually fail under
                // fairly obscure circumstances, even though it is a copy of initialized page pFrom.
                to.IsInit = false;
                var rc = btreeInitPage(to);
                if (rc != RC.OK)
                {
                    rcRef = rc;
                    return;
                }

                // If this is an auto-vacuum database, update the pointer-map entries for any b-tree or overflow pages that pTo now contains the pointers to.
#if !OMIT_AUTOVACUUM
                if (bt.AutoVacuum)
                    rcRef = setChildPtrmaps(to);
#endif
            }
        }
Exemplo n.º 48
0
 // Creates SIP registration of a device/application (WebPhone, Mobile, softphone)
 public Task <CreateSipRegistrationResponse> Post()
 {
     return(RC.Post <CreateSipRegistrationResponse>(Endpoint(true), null));
 }
Exemplo n.º 49
0
 static void ptrmapPutOvflPtr(MemPage page, byte[] cell, ref RC rcRef)
 {
     if (rcRef != RC.OK) return;
     Debug.Assert(cell != null);
     var info = new CellInfo();
     btreeParseCellPtr(page, cell, ref info);
     Debug.Assert((info.Data + (page.IntKey ? 0 : info.Key)) == info.Payload);
     if (info.Overflow != 0)
     {
         Pid ovfl = ConvertEx.Get4(cell, info.Overflow);
         ptrmapPut(page.Bt, ovfl, PTRMAP.OVERFLOW1, page.ID, ref rcRef);
     }
 }
Exemplo n.º 50
0
 // Creates SIP registration of a device/application (WebPhone, Mobile, softphone)
 public Task <CreateSipRegistrationResponse> Post(object parameters)
 {
     return(RC.Post <CreateSipRegistrationResponse>(Endpoint(true), parameters));
 }
Exemplo n.º 51
0
		public void SetImportance(RC.PackageImportance importance, bool match_gteq) {
			rc_package_match_set_importance(Handle, (int) importance, match_gteq);
		}
Exemplo n.º 52
0
 protected override void CalcRowHeight()
 {
     base.CalcRowHeight();
     RowBandHeight = RC.RowHeight;
     RC.SetRowHeight(RowBandHeight * CellBandMap.LevelCount);
 }
Exemplo n.º 53
0
        public RC Step(int pages)
        {
            MutexEx.Enter(SrcCtx.Mutex);
            Src.Enter();
            if (DestCtx != null)
                MutexEx.Enter(DestCtx.Mutex);

            RC rc = RC_;
            if (!IsFatalError(rc))
            {
                Pager srcPager = Src.get_Pager(); // Source pager
                Pager destPager = Dest.get_Pager(); // Dest pager
                Pid srcPage = 0; // Size of source db in pages
                bool closeTrans = false; // True if src db requires unlocking

                // If the source pager is currently in a write-transaction, return SQLITE_BUSY immediately.
                rc = (DestCtx != null && Src.Bt.InTransaction == TRANS.WRITE ? RC.BUSY : RC.OK);

                // Lock the destination database, if it is not locked already.
                if (rc == RC.OK && !DestLocked && (rc = Dest.BeginTrans(2)) == RC.OK)
                {
                    DestLocked = true;
                    Dest.GetMeta(Btree.META.SCHEMA_VERSION, ref DestSchema);
                }

                // If there is no open read-transaction on the source database, open one now. If a transaction is opened here, then it will be closed
                // before this function exits.
                if (rc == RC.OK && !Src.IsInReadTrans())
                {
                    rc = Src.BeginTrans(0);
                    closeTrans = true;
                }

                // Do not allow backup if the destination database is in WAL mode and the page sizes are different between source and destination
                int pgszSrc = Src.GetPageSize(); // Source page size
                int pgszDest = Dest.GetPageSize(); // Destination page size
                IPager.JOURNALMODE destMode = Dest.get_Pager().GetJournalMode(); // Destination journal mode
                if (rc == RC.OK && destMode == IPager.JOURNALMODE.WAL && pgszSrc != pgszDest)
                    rc = RC.READONLY;

                // Now that there is a read-lock on the source database, query the source pager for the number of pages in the database.
                srcPage = Src.LastPage();
                Debug.Assert(srcPage >= 0);
                for (int ii = 0; (pages < 0 || ii < pages) && NextId <= (Pid)srcPage && rc == 0; ii++)
                {
                    Pid srcPg = NextId; // Source page number
                    if (srcPg != Btree.PENDING_BYTE_PAGE(Src.Bt))
                    {
                        IPage srcPgAsObj = null; // Source page object
                        rc = srcPager.Acquire(srcPg, ref srcPgAsObj, false);
                        if (rc == RC.OK)
                        {
                            rc = BackupOnePage(p, srcPg, Pager.GetData(srcPgAsObj), false);
                            Pager.Unref(srcPgAsObj);
                        }
                    }
                    NextId++;
                }
                if (rc == RC.OK)
                {
                    Pagecount = srcPage;
                    Remaining = (srcPage + 1 - NextId);
                    if (NextId > srcPage)
                        rc = RC.DONE;
                    else if (!IsAttached)
                        AttachBackupObject(p);
                }

                // Update the schema version field in the destination database. This is to make sure that the schema-version really does change in
                // the case where the source and destination databases have the same schema version.
                if (rc == RC.DONE)
                {
                    if (srcPage == null)
                    {
                        rc = Dest.NewDb();
                        srcPage = 1;
                    }
                    if (rc == RC.OK || rc == RC.DONE)
                        rc = Dest.UpdateMeta(Btree.META.SCHEMA_VERSION, DestSchema + 1);
                    if (rc == RC.OK)
                    {
                        if (DestCtx != null)
                            Main.ResetAllSchemasOfConnection(DestCtx);
                        if (destMode == IPager.JOURNALMODE.WAL)
                            rc = Dest.SetVersion(2);
                    }
                    if (rc == RC.OK)
                    {
                        // Set nDestTruncate to the final number of pages in the destination database. The complication here is that the destination page
                        // size may be different to the source page size. 
                        //
                        // If the source page size is smaller than the destination page size, round up. In this case the call to sqlite3OsTruncate() below will
                        // fix the size of the file. However it is important to call sqlite3PagerTruncateImage() here so that any pages in the 
                        // destination file that lie beyond the nDestTruncate page mark are journalled by PagerCommitPhaseOne() before they are destroyed
                        // by the file truncation.

                        Debug.Assert(pgszSrc == Src.GetPageSize());
                        Debug.Assert(pgszDest == Dest.GetPageSize());
                        Pid destTruncate;
                        if (pgszSrc < pgszDest)
                        {
                            int ratio = pgszDest / pgszSrc;
                            destTruncate = (Pid)((srcPage + ratio - 1) / ratio);
                            if (destTruncate == Btree.PENDING_BYTE_PAGE(Dest.Bt))
                                destTruncate--;
                        }
                        else
                            destTruncate = (Pid)(srcPage * (pgszSrc / pgszDest));
                        Debug.Assert(destTruncate > 0);

                        if (pgszSrc < pgszDest)
                        {
                            // If the source page-size is smaller than the destination page-size, two extra things may need to happen:
                            //
                            //   * The destination may need to be truncated, and
                            //
                            //   * Data stored on the pages immediately following the pending-byte page in the source database may need to be
                            //     copied into the destination database.
                            int size = (int)(pgszSrc * srcPage);
                            VFile file = destPager.get_File();
                            Debug.Assert(file != null);
                            Debug.Assert((long)destTruncate * (long)pgszDest >= size || (destTruncate == (int)(Btree.PENDING_BYTE_PAGE(Dest.Bt) - 1) && size >= VFile.PENDING_BYTE && size <= VFile.PENDING_BYTE + pgszDest));

                            // This block ensures that all data required to recreate the original database has been stored in the journal for pDestPager and the
                            // journal synced to disk. So at this point we may safely modify the database file in any way, knowing that if a power failure
                            // occurs, the original database will be reconstructed from the journal file.
                            uint dstPage;
                            destPager.Pages(out dstPage);
                            for (Pid pg = destTruncate; rc == RC.OK && pg <= (Pid)dstPage; pg++)
                            {
                                if (pg != Btree.PENDING_BYTE_PAGE(Dest.Bt))
                                {
                                    IPage pgAsObj;
                                    rc = destPager.Acquire(pg, ref pgAsObj, false);
                                    if (rc == RC.OK)
                                    {
                                        rc = Pager.Write(pgAsObj);
                                        Pager.Unref(pgAsObj);
                                    }
                                }
                            }
                            if (rc == RC.OK)
                                rc = destPager.CommitPhaseOne(null, true);

                            // Write the extra pages and truncate the database file as required.
                            long end = Math.Min(VFile.PENDING_BYTE + pgszDest, size);
                            for (long off = VFile.PENDING_BYTE + pgszSrc; rc == RC.OK && off < end; off += pgszSrc)
                            {
                                Pid srcPg = (Pid)((off / pgszSrc) + 1);
                                PgHdr srcPgAsObj = null;
                                rc = srcPager.Acquire(srcPg, ref srcPgAsObj, false);
                                if (rc == RC.OK)
                                {
                                    byte[] data = Pager.GetData(srcPgAsObj);
                                    rc = file.Write(data, pgszSrc, off);
                                }
                                Pager.Unref(srcPgAsObj);
                            }
                            if (rc == RC.OK)
                                rc = BackupTruncateFile(file, (int)size);

                            // Sync the database file to disk. 
                            if (rc == RC.OK)
                                rc = destPager.Sync();
                        }
                        else
                        {
                            destPager.TruncateImage(destTruncate);
                            rc = destPager.CommitPhaseOne(null, false);
                        }

                        // Finish committing the transaction to the destination database.
                        if (rc == RC.OK && (rc = Dest.CommitPhaseTwo(false)) == RC.OK)
                            rc = RC.DONE;
                    }
                }

                // If bCloseTrans is true, then this function opened a read transaction on the source database. Close the read transaction here. There is
                // no need to check the return values of the btree methods here, as "committing" a read-only transaction cannot fail.
                if (closeTrans)
                {
#if !DEBUG || COVERAGE_TEST
                    RC rc2 = Src.CommitPhaseOne(null);
                    rc2 |= Src.CommitPhaseTwo(false);
                    Debug.Assert(rc2 == RC.OK);
#else
                    Src.CommitPhaseOne(null);
                    Src.CommitPhaseTwo(false);
#endif
                }

                if (rc == RC.IOERR_NOMEM)
                    rc = RC.NOMEM;
                RC_ = rc;
            }
            if (DestCtx != null)
                MutexEx.Leave(DestCtx.Mutex);
            Src.Leave();
            MutexEx.Leave(SrcCtx.Mutex);
            return rc;
        }
 // Returns a list of user permissions granted at authorization procedure. Please note: Some permissions may be restricted by extension type.
 public Task <AuthProfileResource> Get()
 {
     return(RC.Get <AuthProfileResource>(Endpoint(true), null));
 }
Exemplo n.º 55
0
		public static string RelationToString(RC.PackageRelation relation, int words) {
			IntPtr raw_ret = rc_package_relation_to_string((int) relation, words);
			string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
			return ret;
		}
Exemplo n.º 56
0
        public static void Run(IRtvBindable target, ICustomTexture fxaaTarget, IDepthStencil depthStencilCopy)
        {
            if (!HasHighlights)
            {
                return;
            }

            ProfilerShort.Begin("MyHighlight.Run");
            MyGpuProfiler.IC_BeginBlock("MyHighlight.Run");
            // set resolved depth/ stencil
            // render all with proper depth-stencil state
            // blur
            // blend to main target testing with stencil again

            MyHighlightPass.Instance.ViewProjection = MyRender11.Environment.Matrices.ViewProjectionAt0;
            MyHighlightPass.Instance.Viewport       = new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y);

            MyHighlightPass.Instance.PerFrame();
            MyHighlightPass.Instance.Begin();

            int samples = MyRender11.Settings.User.AntialiasingMode.SamplesCount();
            IBorrowedRtvTexture rgba8_1 = MyManagers.RwTexturesPool.BorrowRtv("MyHighlight.Rgba8_1", Format.R8G8B8A8_UNorm_SRgb, samples);

            RC.ClearRtv(rgba8_1, new SharpDX.Color4(0, 0, 0, 0));
            RC.SetRtv(depthStencilCopy, MyDepthStencilAccess.DepthReadOnly, rgba8_1);

            foreach (var pair in m_highlights)
            {
                MyActor actor = MyIDTracker <MyActor> .FindByID(pair.Key);

                if (actor == null)
                {
                    MyRenderProxy.Fail("The actor cannot be found for highlight. This bug is outside of the renderer.");
                    continue;
                }
                MyRenderableComponent renderableComponent = actor.GetRenderable();
                MyInstanceComponent   instanceComponent   = actor.GetInstance();
                if (renderableComponent != null)
                {
                    DrawRenderableComponent(actor, renderableComponent, pair.Value);
                }
                else if (instanceComponent != null)
                {
                    DrawInstanceComponent(instanceComponent, pair.Value);
                }
                else
                {
                    // If an actor has been removed without removing outlines, just remove the outlines too
                    m_keysToRemove.Add(pair.Key);
                    MyRenderProxy.Fail("The actor has been removed, but the highligh is still active. This bug is caused by the issue out of the renderer.");
                }
            }

            MyHighlightPass.Instance.End();
            RC.SetBlendState(null);
            foreach (var outlineKey in m_keysToRemove)
            {
                m_highlights.Remove(outlineKey);
            }
            m_keysToRemove.Clear();

            ISrvBindable initialSourceView = rgba8_1;
            IRtvBindable renderTargetview  = rgba8_1;

            float maxThickness = 0f;

            foreach (var pair in m_highlights)
            {
                foreach (MyHighlightDesc descriptor in pair.Value)
                {
                    maxThickness = Math.Max(maxThickness, descriptor.Thickness);
                }
            }

            if (maxThickness > 0)
            {
                IBorrowedRtvTexture rgba8_2 = MyManagers.RwTexturesPool.BorrowRtv("MyHighlight.Rgba8_2", Format.R8G8B8A8_UNorm_SRgb);
                MyBlur.Run(renderTargetview, rgba8_2, initialSourceView,
                           (int)Math.Round(maxThickness), MyBlur.MyBlurDensityFunctionType.Exponential, 0.25f,
                           MyDepthStencilStateManager.IgnoreDepthStencil);
                rgba8_2.Release();
            }

            MyGpuProfiler.IC_EndBlock();
            ProfilerShort.End();

            BlendHighlight(target, rgba8_1, fxaaTarget, depthStencilCopy);
        }
Exemplo n.º 57
0
 public void AddUpdate(RC.PackageUpdate update) {
     rc_package_add_update(Handle, update == null ? IntPtr.Zero : update.Handle);
     update.Owned = false;
 }
Exemplo n.º 58
0
 // Get Extension Phone Numbers
 public Task <ListResponse> List()
 {
     return(RC.Get <ListResponse>(Endpoint(false), null));
 }
Exemplo n.º 59
0
        private void AppendDiff(bool diffCacheEnabled, XDoc body, RecentChangeEntry change, RC type, Title title, IDictionary<string, XDoc> cache) {
            var resources = DekiContext.Current.Resources;
            ulong pageid = change.CurId;
            int? after = (change.Revision > 0) ? (int?)change.Revision : null;
            int? before = change.PreviousRevision;

            // append edit summary, if any
            body.Elem("p", change.Summary);

            // append comment(s)
            int count = (change.ExtraComments == null) ? (string.IsNullOrEmpty(change.Comment) ? 0 : 1) : change.ExtraComments.Count;
            switch(count) {
            case 0:

                // nothing to do
                break;
            case 1:
                body.Elem("p", (change.ExtraComments != null) ? change.ExtraComments[0].Item3 : change.Comment);
                break;
            default:
                body.Start("ol");
                foreach(var comment in ((IEnumerable<Tuplet<string, string, string>>)change.ExtraComments).Reverse()) {
                    string author = string.IsNullOrEmpty(comment.Item2) ? comment.Item1 : comment.Item2;
                    body.Elem("li", string.IsNullOrEmpty(author) ? comment.Item3 : string.Format("{0} ({1})", comment.Item3, author));
                }
                body.End();
                break;
            }

            // check if page was modified
            if(after.HasValue && before.HasValue && (after != before)) {

                // check if we have a cached version of this page diff
                XDoc diffXml = null;
                Plug store = Storage.At("site_" + XUri.EncodeSegment(DekiContext.Current.Instance.Id), DreamContext.Current.Culture.Name, "feeds", string.Format("page_{0}", pageid), string.Format("diff_{0}-{1}.xml", before, after));
                if(diffCacheEnabled) {
                    var v = store.Get(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
                    diffXml = (v.IsSuccessful && v.HasDocument) ? v.ToDocument() : null;

                    if(diffXml != null) {

                        // TODO (steveb): this problem only exists b/c we can't determine the actual revision number that we should use for diffing (see bug 7824)

                        // check if either revision has been hidden since we computed the diff
                        var session = DbUtils.CurrentSession;
                        if(after.Value != change.CurrentRevision) {
                            OldBE afterRevision = session.Old_GetOldByRevision(pageid, (ulong)after.Value);
                            if((afterRevision == null) || afterRevision.IsHidden) {
                                diffXml = null;
                            }
                        }
                        if((diffXml != null) && (before.Value != change.CurrentRevision) && (before.Value > 0)) {
                            OldBE beforeRevision = session.Old_GetOldByRevision(pageid, (ulong)before.Value);
                            if((beforeRevision == null) || beforeRevision.IsHidden) {
                                diffXml = null;
                            }
                        }
                    }
                }
                if(diffXml == null) {
                    diffXml = new XDoc("diff");

                    // retrieve page versions
                    XDoc res = QueryPageVersions(pageid, after, before, cache);
                    XDoc beforeDoc = res["before/body"];
                    XDoc afterDoc = res["after/body"];

                    // check if either both versions or only one version were retrieved
                    XDoc diff = XDoc.Empty;
                    XDoc invisibleDiff = XDoc.Empty;
                    string summary = null;
                    if(!beforeDoc.IsEmpty && !afterDoc.IsEmpty) {
                        XDoc beforeChanges;
                        XDoc afterChanges;
                        DekiResource summaryResource = null;

                        // compute differences between 'before' and 'after' versions
                        diff = Utils.GetPageDiff(beforeDoc, afterDoc, true, DekiContext.Current.Instance.MaxDiffSize, out invisibleDiff, out summaryResource, out beforeChanges, out afterChanges);

                        // TODO (arnec): why are we using ToLower here at all and without a culture?
                        summary = resources.Localize(summaryResource).ToLower();
                    } else if(!afterDoc.IsEmpty) {

                        // since we don't have a 'before' version, just show the entire 'after' version (can happen for new pages or hidden revisions)
                        diff = afterDoc;
                    } else if(!beforeDoc.IsEmpty) {

                        // since we don't have a 'after' version, just show the entire 'before' version (can happen for hidden revisions)
                        diff = beforeDoc;
                    }

                    // add change summary
                    diffXml.Start("blockquote");
                    diffXml.Start("p").Elem("strong", summary).End();

                    // check if a diff was computed
                    if(!diff.IsEmpty) {
                        diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End();
                        diffXml.AddNodes(diff);
                        diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End();

                        // check if there are invisible changes as well to show
                        if(!invisibleDiff.IsEmpty) {
                            diffXml.Start("p").Elem("strong", resources.Localize(DekiResources.PAGE_DIFF_OTHER_CHANGES())).End();
                            diffXml.Add(invisibleDiff);
                        }
                    } else if(!invisibleDiff.IsEmpty) {

                        // only show invisible changes
                        diffXml.Start("hr").Attr("width", "100%").Attr("size", "2").End();
                        diffXml.Start("p").Elem("strong", resources.Localize(DekiResources.PAGE_DIFF_OTHER_CHANGES())).End();
                        diffXml.Add(invisibleDiff);
                    } else if(beforeDoc.IsEmpty && afterDoc.IsEmpty) {

                        // show message that page contents were not available anymore
                        diffXml.Elem("p", resources.Localize(DekiResources.PAGE_NOT_AVAILABLE()));
                    }
                    diffXml.End();

                    // store diff in cache
                    if(diffCacheEnabled && !afterDoc.IsEmpty) {
                        store.With("ttl", TimeSpan.FromDays(30).TotalSeconds).Put(diffXml, new Result<DreamMessage>(TimeSpan.MaxValue)).Block();
                    }
                }
                body.AddNodes(diffXml);
            }

            // check if we have a comment text
            if(Utils.IsPageComment(type)) {
                string text = change.CmntContent;
                if(!string.IsNullOrEmpty(text) && !change.CmntDeleted) {
                    MimeType mime = new MimeType(change.CmntMimetype ?? MimeType.TEXT_UTF8.ToString());
                    if(mime.Match(MimeType.HTML)) {
                        XDoc html = XDocFactory.From(string.Format("<html><body>{0}</body></html>", text), MimeType.HTML);
                        body.Start("blockquote").AddNodes(html["body"]).End();
                    } else {

                        // anything else should be consider to be text
                        body.Start("blockquote").Elem("p", text).End();
                    }
                } else {

                    // anything else should be consider to be text
                    body.Start("blockquote").Elem("p", resources.Localize(DekiResources.COMMENT_NOT_AVAILABLE())).End();
                }
            }

            // adds links
            body.Start("table").Attr("border", 0).Attr("padding", "5").Attr("width", "80%").Start("tr");

            // add link for viewing the page
            if(change.PageExists) {
                Title view = new Title(title);
                body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(view, true)).Value(resources.Localize(DekiResources.VIEW_PAGE())).End().End();
            }

            // check if we need to add link for editing the page
            if(after.HasValue && before.HasValue && (after != before)) {
                Title edit = new Title(title) { Query = "action=edit" };
                body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(edit)).Value(resources.Localize(DekiResources.EDIT_PAGE())).End().End();
            }

            // check if we need to add link for viewing the complete diff
            if(after.HasValue && before.HasValue && (after != before)) {
                Title show = new Title(title) { Query = string.Format("diff={0}&revision={1}", after.Value, before.Value) };
                body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(show, true)).Value(resources.Localize(DekiResources.VIEW_PAGE_DIFF())).End().End();
            }

            // check if we need to add link for seeing full page history
            if(after.HasValue && before.HasValue && (after != before)) {
                Title history = new Title(title) { Query = "action=history" };
                body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(history)).Value(resources.Localize(DekiResources.VIEW_PAGE_HISTORY())).End().End();
            }

            // check if we need to add link for banning the user
            List<KeyValuePair<string, string>> authors = change.SortedAuthors;
            if((authors == null) || (authors.Count == 0)) {
                authors = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(change.Username, change.Fullname) };
            }
            for(int i = 0; i < authors.Count; ++i) {
                string username = authors[i].Key;
                string fullname = authors[i].Value;
                if(!string.IsNullOrEmpty(username)) {

                    // don't put up ban link for admins.
                    UserBE user = DbUtils.CurrentSession.Users_GetByName(username);
                    if(!UserBL.IsAnonymous(user) && !PermissionsBL.IsUserAllowed(user, Permissions.ADMIN)) {
                        Title ban = Title.FromUIUri(null, "Special:Userban");
                        ban.Query += string.Format("username={0}", username);
                        body.Start("td").Start("a").Attr("href", Utils.AsPublicUiUri(ban)).Value(resources.Localize(DekiResources.BAN_USER(string.IsNullOrEmpty(fullname) ? username : fullname))).End().End();
                    }
                }
            }

            // close HTML
            body.End().End();
        }
Exemplo n.º 60
0
 // Get Extension Phone Numbers
 public Task <ListResponse> List(object parameters)
 {
     return(RC.Get <ListResponse>(Endpoint(false), parameters));
 }