예제 #1
0
    private void _doGet(IDbConnection conn, XmlElement ds) {
      var logger = new Logger(this.BioSession.Cfg.WorkspacePath, "debug.log") { Disabled = true };
      var cursor = new CJSCursor(conn, ds, this.bioCode);
      var rqst = this.BioRequest<JsonStoreRequestGet>();
      logger.WriteLn("_doGet - start");
      cursor.Init(rqst);
      logger.WriteLn("_doGet - cursor.Init - done");
      cursor.Open(rqst.Timeout);
      logger.WriteLn("_doGet - cursor.Open - done");
      try {
        var sqlToJson = new CSQLtoJSON();
        var packet = sqlToJson.Process(cursor, logger);
        var rsp = new JsonStoreResponse {
          BioParams = this.bioParams,
          Ex = null,
          Success = true,
          TransactionID = this.TransactionID,
          packet = packet,
        };
        logger.WriteLn("_doGet - sqlToJson.Process - done");

        this.Context.Response.Write(rsp.Encode());
        logger.WriteLn("_doGet - Response.Write - done");
      } finally {
        cursor.Close();
      }
      logger.WriteLn("_doGet - end");
    }
예제 #2
0
    public void PrepareSQL(String selection, CJSCursor cursor, ref String sql) {
      this.FInvert = this.extractInvert(selection);
      this.FPKs = this.extractPKS(selection, cursor);

      String vWhereSQL = null;
      String vInvertStr = "";
      if(this.Invert)
        vInvertStr = "not ";
      foreach(var pk in this.PKs) {
        String oneCond = null;
        foreach(var fldItem in ((Params)pk.InnerObject)) {
          var fld = (Field)fldItem.InnerObject;
          Utl.AppendStr(ref oneCond, fld.FieldName + " = " + ":" + fld.FieldName + "", " and ");
          cursor.Params.Add(fld.FieldName, fldItem.Value);
        }
        if(vWhereSQL == null)
          vWhereSQL = " " + vInvertStr + "(" + oneCond + ")";
        else
          vWhereSQL += " and " + vInvertStr + "(" + oneCond + ")";
      }

      if(vWhereSQL != null)
        sql = String.Format("SELECT * FROM ({0}) WHERE {1}", sql, vWhereSQL);

    }
예제 #3
0
 private IDbCommand _prepareCmdDelegate(IDbConnection conn, ref String currentSQL, ref Params currentParams) {
   IDbCommand stmt = null;
   XmlElement vDS = this.FBioDesc.DocumentElement;
   if (vDS != null) {
     CJSCursor vCursor = new CJSCursor(conn, vDS, this.bioCode);
     currentParams = (Params)this.bioParams.Clone();
     stmt = vCursor.DoPrepareCommand(currentParams, ref currentSQL, 0);
   }
   return stmt;
 }
예제 #4
0
    protected override void doExecute() {
      base.doExecute();
      EBioException ebioex = null;
      if (this.FBioDesc == null)
        throw new EBioException(String.Format("Описание объекта {0} не найдено на сервере.", this.bioCode));

      var vDS = this.FBioDesc.DocumentElement;
      if (vDS == null) 
        throw new EBioException(String.Format("В описании объекта {0} не найден раздел <store>.", this.bioCode));

      var v_hashCodeOfFile = Params.FindParamValue(this.QParams, CS_HASH_CODE_WEB_PARAM) as String;
      if (String.IsNullOrEmpty(v_hashCodeOfFile)) 
        throw new EBioException(String.Format("В параметрах запроса должен присутствовать параметр {0}.", CS_HASH_CODE_WEB_PARAM));

        var rqst = this.BioRequest<BioRequest>();
        var vConn = this.BioSession.Cfg.dbSession.GetConnection();
        try {
          try {
            var cursor = new CJSCursor(vConn, vDS, this.bioCode);
            var ajaxRequestTimeOut = Utl.Convert2Type<int>(Params.FindParamValue(this.QParams, "ajaxrqtimeout"));
            var vMon = SQLGarbageMonitor.GetSQLGarbageMonitor(this.Context);
            vMon.RegisterSQLCmd(cursor, (SQLCmd vSQLCmd, ref Boolean killQuery, ref Boolean killSession, Boolean vAjaxTimeoutExceeded) => {
              if (Equals(cursor, vSQLCmd)) {
                killQuery = !this.Context.Response.IsClientConnected || vAjaxTimeoutExceeded;
                killSession = killQuery;
              }
            }, ajaxRequestTimeOut);
            try {
              var prms = new Params();
              prms.Add("p_hash_code", v_hashCodeOfFile);
              prms.Add(new Param(CS_FILE_NAME_PARAM, null, typeof(String), ParamDirection.Output));
              prms.Add(new Param(CS_FILE_PARAM, null, typeof(Byte[]), ParamDirection.Output));
              cursor.DoExecuteSQL(prms, 120);
              this._sendFileToClient(prms);
            } catch (Exception ex) {
              throw EBioException.CreateIfNotEBio(ex);
            } finally {
              vMon.RemoveItem(cursor);
            }
          } catch (Exception ex) {
            vConn.Close();
            vConn.Dispose();
            throw EBioException.CreateIfNotEBio(ex);
          }
        } catch (Exception ex) {
          ebioex = new EBioException("Ошибка выполнения на сервере. Сообщение: " + ex.Message, ex);
        } 
      if (ebioex != null) {
        this.Context.Response.Write(new BioResponse() { Success = false, BioParams = this.bioParams, Ex = ebioex }.Encode());
      }
    }
예제 #5
0
    private Params extractPKItem(String pBioSelItem, CJSCursor pCur) {
      Params vRslt = new Params();
      String vBioSelItem = pBioSelItem;
      this.killTrailerChars(ref vBioSelItem, '(', ')');
      String[] vBioSelItemVals = Utl.SplitString(vBioSelItem, ")-(");
      for(int i = 0; i < vBioSelItemVals.Length; i++) {
        String vKey = "" + (i + 1);
        if(pCur.PKFields.ContainsKey(vKey)) {
          Field vPKFld = (Field)pCur.PKFields[vKey];
          vRslt.Add(vPKFld.FieldName, vBioSelItemVals[i], vPKFld);
        }
      }
      return vRslt;

    }
예제 #6
0
 private void _loadDocFromCursor(XmlElement ds, StringBuilder doc, ref EBioException v_ex) {
   using (var vConn = this.BioSession.Cfg.dbSession.GetConnection()) {
     try {
       var vCursor = new CJSCursor(vConn, ds, this.bioCode);
       var v_request = this.BioRequest<JsonStoreRequestGet>();
       vCursor.Init(v_request);
       try {
         this.processData(vCursor, doc, ref v_ex);
       } finally {
         vCursor.Close();
       }
     } catch (Exception ex) {
       v_ex = EBioException.CreateIfNotEBio(ex);
     } finally {
       if (vConn != null)
         vConn.Close();
     }
   }
 }
예제 #7
0
 protected override void doExecute() {
   base.doExecute();
   EBioException ebioex = null;
   if (this.FBioDesc == null)
     throw new EBioException(String.Format("Описание объекта {0} не найдено на сервере.", this.bioCode));
   var vDS = this.FBioDesc.DocumentElement;
   if (vDS != null) {
     var rqst = this.BioRequest<BioSQLRequest>();
     var vConn = this.AssignTransaction(vDS, rqst);
     try {
       var vCursor = new CJSCursor(vConn, vDS, this.bioCode);
       var vAjaxRequestTimeOut = Utl.Convert2Type<int>(Params.FindParamValue(this.QParams, "ajaxrqtimeout"));
       var vMon = SQLGarbageMonitor.GetSQLGarbageMonitor(this.Context);
       vMon.RegisterSQLCmd(vCursor, (SQLCmd vSQLCmd, ref Boolean killQuery, ref Boolean killSession, Boolean vAjaxTimeoutExceeded) => {
         if (Equals(vCursor, vSQLCmd)) {
           killQuery = !this.Context.Response.IsClientConnected || vAjaxTimeoutExceeded;
           killSession = killQuery;
         }
       }, vAjaxRequestTimeOut);
       try {
         vCursor.DoExecuteSQL(this.bioParams, rqst.Timeout);
         this.Context.Response.Write(
           new BioResponse {
             Success = true,
             TransactionID = !this.AutoCommitTransaction ? this.TransactionID : null,
             BioParams = this.bioParams
           }.Encode());
       } finally {
         vMon.RemoveItem(vCursor);
       }
     } catch (Exception ex) {
       this.FinishTransaction(vConn, true, SQLTransactionCmd.Rollback);
       ebioex = new EBioException("Ошибка выполнения на сервере. Сообщение: " + ex.Message, ex);
     } finally {
       this.FinishTransaction(vConn, true, rqst.transactionCmd);
     }
   } else
     ebioex = new EBioException("В описании объекта [" + this.bioCode + "] не найден раздел <store>.");
   if (ebioex != null) {
     this.Context.Response.Write(new BioResponse { Success = false, BioParams = this.bioParams, Ex = ebioex }.Encode());
   }
 }
예제 #8
0
    /// <summary>
    /// Запускает процесс обработки данных курсора и возвращает строку в виде JSON-объекта.
    /// </summary>
    /// <param name="cursor">Созданный курсор.</param>
    /// <param name="logFile"></param>
    /// <returns>CJsonStoreData</returns>
    public JsonStoreData Process(CJSCursor cursor, Logger logger = null) {
      if (logger != null) logger.WriteLn("CSQLtoJSON.Process - start");
      var result = new JsonStoreData {
        EndReached = cursor.rqPacket.EndReached,
        Start = 0
      };

      result.MetaData = JsonStoreMetadata.ConstructMetadata(cursor.bioCode, cursor.CursorIniDoc);
      result.Rows = new JsonStoreRows();
      var rowCount = 0;
      result.Start = cursor.rqPacket.Start;
      result.Limit = cursor.rqPacket.Limit;
      result.TotalCount = cursor.rqPacket.TotalCount;
      // перебираем все записи в курсоре
      //throw new Exception("FTW!!!");
      if (logger != null) logger.WriteLn("CSQLtoJSON.Process - cursor - fettching - start");
      while (cursor.Next()) {
        if (result.Limit == 0 || ++rowCount <= result.Limit) {
          var newRow = result.AddRow();
          // перебираем все поля одной записи
          if (logger != null) logger.WriteLn("CSQLtoJSON.Process - cursor - fields - fettching - start");
          foreach (var fld in cursor.Fields) {
            var fieldName = fld.FieldName;
            var v_field = fld;
            var process = true;
            if (this.ProcessField != null)
              process = this.ProcessField(ref fieldName, ref v_field);
            if (process) {
              var doEncodeFromAnsi = (v_field.DataType == JSFieldType.Clob) && (v_field.Encoding == FieldEncoding.WINDOWS1251);
              newRow.Values[result.MetaData.IndexOf(fieldName)] = doEncodeFromAnsi ? Utl.EncodeANSI2UTF(v_field.AsObject as String) : v_field.AsObject;
            }
          }
          if (logger != null) logger.WriteLn("CSQLtoJSON.Process - cursor - fields - fettching - end");
        }
      }
      if (logger != null) logger.WriteLn("CSQLtoJSON.Process - cursor - fettching - end");
      result.EndReached = result.Limit == 0 || rowCount <= result.Limit;
      result.TotalCount = result.Start + rowCount;
      if (logger != null) logger.WriteLn("CSQLtoJSON.Process - end");
      return result;
    }
예제 #9
0
 private void _loadDocFromProc(XmlElement ds, StringBuilder doc, ref EBioException v_ex) {
   using (var vConn = this.BioSession.Cfg.dbSession.GetConnection()) {
     try {
       var vCursor = new CJSCursor(vConn, ds, this.bioCode);
       var v_request = this.BioRequest<JsonStoreRequestGet>();
       vCursor.DoExecuteSQL(v_request.BioParams, 120);
       var v_out_prm = v_request.BioParams.Where((p) => {
         return (p.ParamDir == ParamDirection.InputOutput) ||
                  (p.ParamDir == ParamDirection.Output) ||
                    (p.ParamDir == ParamDirection.Return);
       }).FirstOrDefault();
       if (v_out_prm != null)
         doc.Append(v_out_prm.Value);
     } catch (Exception ex) {
       v_ex = EBioException.CreateIfNotEBio(ex);
     } finally {
       if (vConn != null)
         vConn.Close();
     }
   }
 }
예제 #10
0
    private void processData(CJSCursor pCursor, StringBuilder vDoc, ref EBioException vEx) {
      try {
        var needClose = false;
        if(!pCursor.IsActive && (pCursor.Connection != null)) {
          pCursor.Open(120);
          needClose = true;
        }
      // перебираем все записи в курсоре
        while(pCursor.Next()) {
          // перебираем все поля одной записи
          var fRow = new StringBuilder();
          foreach(DictionaryEntry vCur in pCursor.RowValues) {
            fRow.Append(SQLUtils.ObjectAsString(vCur.Value));
          }
          vDoc.Append(fRow);
        }
        if(needClose)
          pCursor.Close();
      } catch(Exception ex) {
        vEx = EBioException.CreateIfNotEBio(ex);
      }

    }
예제 #11
0
 private Params extractPKS(String pBioSelection, CJSCursor pCur) {
   Params vRslt = new Params();
   String vRsltStr = null;
   Regex vr = new Regex("\"pks\" *: *.+}", RegexOptions.IgnoreCase);
   Match m = vr.Match(pBioSelection);
   if(m.Success) {
     String[] vPrts = Utl.SplitString(m.Value, ':');
     if(vPrts.Length == 2)
       vRsltStr = vPrts[1].Trim().Substring(0, vPrts[1].Length - 1);
   }
   if(vRsltStr != null) {
     killTrailerChars(ref vRsltStr, '[', ']');
     String[] vRows = Utl.SplitString(vRsltStr, ',');
     for(int i = 0; i < vRows.Length; i++ ) {
       String vStrItem = vRows[i];
       vStrItem = vStrItem.Trim();
       this.killTrailerChars(ref vStrItem, '"', '"');
       Params vPKRow = this.extractPKItem(vStrItem, pCur);
       vRslt.Add("ROW_ID", vStrItem, vPKRow);
     }
   }
   return vRslt;
 }
예제 #12
0
 private void _doProcessCursor() {
   var conn = this.dbSess.GetConnection();
   var vCursor = new CJSCursor(conn, this._cursor_ds, this.bioCode);
   vCursor.Init(null, this._request.BioParams, this._request.Filter, this._request.Sort, this._request.Selection, 120);
   vCursor.Open(120);
   try {
     while (vCursor.Next()) {
       if (this._state == RemoteProcState.Breaking)
         break;
       var newRow = vCursor.rqPacket.MetaData.CreateNewRow();
       // перебираем все поля одной записи
       foreach (Field vCur in vCursor.Fields) {
         var vFName = vCur.FieldName;
         var vFVal = vCur;
         newRow.Values[vCursor.rqPacket.MetaData.IndexOf(vFName)] = vCur.AsObject;
       }
       this._doProcessRecord(vCursor.rqPacket.MetaData, newRow);
     }
   } finally {
     vCursor.Close();
     if (conn != null)
       conn.Close();
   }
 }
예제 #13
0
 private void _doProcessRecord(JsonStoreMetadata metadata, JsonStoreRow row) {
   var conn = this.dbSess.GetConnection();
   try {
     var vCmd = new CJSCursor(conn, this._exec_ds, this._request.ExecBioCode);
     vCmd.DoExecuteSQL(metadata, row, this._request.BioParams, 120);
   } finally {
     if (conn != null)
       conn.Close();
   }
 }
예제 #14
0
    private void _doGetSelectionPks(IDbConnection conn, XmlElement ds) {
      var v_cursor = new CJSCursor(conn, ds, this.bioCode);
      var rqst = this.BioRequest<JsonStoreRequestGet>();
      v_cursor.Init(rqst);
      v_cursor.Open(rqst.Timeout);
      try {
        String pks = null;
        while (v_cursor.Next()) 
          Utl.AppendStr(ref pks, v_cursor.PKValue, ";");
        var rsp = new JsonStoreResponse {
          BioParams = this.bioParams,
          Ex = null,
          Success = true,
          TransactionID = this.TransactionID,
          selectedPkList = pks
        };

        this.Context.Response.Write(rsp.Encode());
      } finally {
        v_cursor.Close();
      }
    }