private static VPC.Entities.BatchType.BatchType ReadBatchType(SqlDataReader reader)
        {
            var info     = new VPC.Entities.BatchType.BatchType();
            var tenantId = reader.IsDBNull(0) ? Guid.Empty : reader.GetGuid(0);
            var id       = reader.IsDBNull(1) ? Guid.Empty : reader.GetGuid(1);
            BatchTypeContextEnum context = reader.IsDBNull(2) ? BatchTypeContextEnum.Email : (BatchTypeContextEnum)reader.GetInt16(2);
            BatchTypeEnum        type    = reader.IsDBNull(3) ? BatchTypeEnum.Indefinite : (BatchTypeEnum)reader.GetByte(3);
            byte?priority       = reader.IsDBNull(4) ? (byte?)null : reader.GetByte(4);
            int? idleTime       = reader.IsDBNull(5) ? (int?)null : reader.GetInt32(5);
            int? itemTimeOut    = reader.IsDBNull(6) ? (int?)null : reader.GetInt32(6);
            int? itemRetryCount = reader.IsDBNull(7) ? (int?)null : reader.GetInt16(7);

            System.DateTime?startDate   = reader.IsDBNull(8) ? (System.DateTime?)null : reader.GetDateTime(8);
            System.DateTime?endDate     = reader.IsDBNull(9) ? (System.DateTime?)null : reader.GetDateTime(9);
            var             schedulerId = reader.IsDBNull(10) ? Guid.Empty : reader.GetGuid(10);

            info.TenantId       = new InternalId();
            info.TenantId.Value = tenantId.ToString();

            info.InternalId       = new InternalId();
            info.InternalId.Value = id.ToString();

            info.Context       = new PickList <BatchTypeContext>();
            info.Context.Value = ((int)context).ToString();

            info.Type       = new PickList <BatchTypes>();
            info.Type.Value = ((int)type).ToString();

            info.Priority       = new NumericType();
            info.Priority.Value = priority.HasValue ?  priority.ToString() : string.Empty;

            info.IdleTime       = new NumericType();
            info.IdleTime.Value = idleTime.HasValue ?  idleTime.ToString() : string.Empty;

            info.ItemTimeout       = new NumericType();
            info.ItemTimeout.Value = itemTimeOut.HasValue ?  itemTimeOut.ToString() : string.Empty;

            info.ItemRetryCount       = new NumericType();
            info.ItemRetryCount.Value = itemRetryCount.HasValue ?  itemRetryCount.ToString() : string.Empty;

            info.StartDate       = new VPC.Metadata.Business.DataTypes.DateTime();
            info.StartDate.Value = startDate.ToString();

            info.EndDate       = new VPC.Metadata.Business.DataTypes.DateTime();
            info.EndDate.Value = endDate.ToString();

            info.Scheduler                  = new BatchTypeScheduler();
            info.Scheduler.InternalId       = new InternalId();
            info.Scheduler.InternalId.Value = schedulerId.ToString();
            return(info);
        }
        internal VPC.Entities.BatchType.BatchType GetBatchTypeByContext(Guid tenantId, BatchTypeContextEnum context)
        {
            VPC.Entities.BatchType.BatchType batche = null;
            try
            {
                SqlProcedureCommand cmd = CreateProcedureCommand("dbo.BatchType_GetByContext");
                cmd.AppendGuid("@guidTenantId", tenantId);
                cmd.AppendSmallInt("@siContext", (short)context);
                using (SqlDataReader reader = ExecuteCommandAndReturnReader(cmd))
                {
                    while (reader.Read())
                    {
                        batche = ReadBatchType(reader);
                    }
                }
            }
            catch (SqlException e)
            {
                throw ReportAndTranslateException(e, "DataBatchType::BatchType_GetByContext");
            }

            return(batche);
        }
        void IBatchTypes.OnExecute(dynamic obj)
        {
            VPC.Entities.BatchType.BatchType batchType = (VPC.Entities.BatchType.BatchType)obj[0];
            var tenantId = Guid.Parse(batchType.TenantId.Value);

            try
            {
                var allBatchItems = _managerBatchItem.GetBatchItems(tenantId, new Guid(batchType.InternalId.Value), (batchType.ItemRetryCount.Value.Length > 0 ? (int?)Int32.Parse(batchType.ItemRetryCount.Value) : (int?)null));
                foreach (var allBatchItem in allBatchItems)
                {
                    try
                    {
                        var queryFilter1 = new List <QueryFilter> ();
                        queryFilter1.Add(new QueryFilter {
                            FieldName = "TenantId", Operator = "Equal", Value = tenantId.ToString()
                        });
                        var queryContext1 = new QueryContext {
                            Fields = "FirstName,LastName", Filters = queryFilter1, PageSize = 100, PageIndex = 1
                        };
                        DataTable templatedt = _queryManager.GetResult(tenantId, "user", queryContext1);


                        _managerBatchItem.BatchItemUpdateStartTime(tenantId, allBatchItem.BatchItemId);
                        var excelByte = GenerateExcel(tenantId, batchType, templatedt);

                        //Update batch History
                        _managerBatchItem.BatchHistoryCreate(tenantId, new BatchItemHistory {
                            BatchHistoryId = Guid.NewGuid(),
                            BatchItemId    = allBatchItem.BatchItemId,
                            EntityId       = allBatchItem.EntityId,
                            ReferenceId    = allBatchItem.ReferenceId,
                            Status         = EmailEnum.Send,
                            RunTime        = allBatchItem.NextRunTime
                        });

                        //Send email for attachment
                        JObject userJObject = new JObject();
                        userJObject.Add(new JProperty("FirstName", "Ajay chouhan"));
                        var template  = _iEntityResourceManager.GetWellKnownTemplate(tenantId, "Emailtemplate", "User", (int)ContextTypeEnum.ExportUser, userJObject);
                        var returnVal = DataUtility.SaveEmail(tenantId, Guid.Empty, template, "*****@*****.**", "ExportUser", InfoType.User);

                        _managerBatchItem.BatchContentCreate(tenantId, new Entities.BatchType.BatchItemContent {
                            BatchItemContentId = Guid.NewGuid(),
                            BatchItemId        = returnVal,
                            Content            = Convert.ToBase64String(excelByte),
                            Name     = "ExportUser",
                            MimeType = "application/vnd.ms-excel",
                        });
                    }
                    catch (System.Exception ex)
                    {
                        _log.Error("An error has occurred while sending email", ex.Message);

                        //Update batch History
                        _managerBatchItem.BatchHistoryCreate(tenantId, new BatchItemHistory {
                            BatchHistoryId = Guid.NewGuid(),
                            BatchItemId    = allBatchItem.BatchItemId,
                            EntityId       = allBatchItem.EntityId,
                            ReferenceId    = allBatchItem.ReferenceId,
                            Status         = EmailEnum.Fail,
                            RunTime        = allBatchItem.NextRunTime,
                            FailedReason   = ex.Message
                        });
                        //Update Batch item status
                        _managerBatchItem.BatchItemUpdate(tenantId, (batchType.ItemRetryCount.Value.Length > 0 ? (int?)Int32.Parse(batchType.ItemRetryCount.Value) : (int?)null),
                                                          new BatchItem {
                            BatchItemId  = allBatchItem.BatchItemId,
                            Status       = EmailEnum.Fail,
                            FailedReason = ex.Message
                        });
                        //Update Email Status
                        // _iEntityResourceManager.UpdateSpecificField(tenantId, "email", allBatchItem.ReferenceId, "Status", ((int)EmailEnum.Fail).ToString());
                        throw ex;
                    }

                    //Update Batch item status
                    _managerBatchItem.BatchItemUpdateStatus(tenantId, new BatchItem {
                        Status = EmailEnum.Send, BatchItemId = allBatchItem.BatchItemId
                    });
                }
            }
            catch (System.Exception ex)
            {
                _log.Error("ImportProductBatch failed", ex.Message);
            }
        }
        private byte[] GenerateExcel(Guid tenantId, VPC.Entities.BatchType.BatchType batchType, DataTable dataTable)
        {
            SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

            // if (!ModelState.IsValid)
            //   return View(model);

            var options   = GetSaveOptions("XLSX");
            var workbook  = new ExcelFile();
            var worksheet = workbook.Worksheets.Add("Sheet1");

            //var style = worksheet.Rows[0].Style;
            //style.Font.Weight = ExcelFont.BoldWeight;
            // style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
            // worksheet.Columns[0].Style.HorizontalAlignment = HorizontalAlignmentStyle.Center;

            // worksheet.Columns[0].SetWidth(50, LengthUnit.Pixel);
            //worksheet.Columns[1].SetWidth(150, LengthUnit.Pixel);

            worksheet.Cells["A1"].Value = "First Name";
            worksheet.Cells["B1"].Value = "Last Name";


            int rowCount = 0;

            foreach (DataRow row in dataTable.Rows)
            {
                int i = 0;
                foreach (DataColumn col in dataTable.Columns)
                {
                    if (col.ColumnName == "FirstName")
                    {
                        worksheet.Cells[rowCount, i].Value = row[col].ToString();
                    }

                    if (col.ColumnName == "LastName")
                    {
                        worksheet.Cells[rowCount, i].Value = row[col].ToString();
                    }

                    i++;
                }
                rowCount++;
            }
            var fileBytes = GetBytes(workbook, options);

            //byte[] fileBytes= new byte[stream.Length];

            //stream.Read(fileBytes, 0, fileBytes.Length);
            // stream.Close();
            //Begins the process of writing the byte array back to a file

            // using (Stream file = File.OpenWrite(@"D:\UserExport.XLSX"))
            // {
            // file.Write(fileBytes, 0, fileBytes.Length);
            // }

            return(fileBytes);


            //  if (!File.Exists("Create.XLSX"))
            //     {
            //         using (var sw = File.CreateText(Path))
            //         {
            //             sw.WriteLine("Ajay chouhan");
            //         }
            //     }



            // return File(GetBytes(workbook, options), options.ContentType, "Create." + model.SelectedFormat.ToLowerInvariant());
        }
        void IBatchTypes.OnExecute(dynamic obj)
        {
            VPC.Entities.BatchType.BatchType batchType = (VPC.Entities.BatchType.BatchType)obj[0];
            var tenantId = Guid.Parse(batchType.TenantId.Value);

            try
            {
                ISettingManager        _iSettingManager        = new SettingManager();
                IEntityResourceManager _iEntityResourceManager = new VPC.Framework.Business.EntityResourceManager.Contracts.EntityResourceManager();
                IManagerBatchItem      _managerBatchItem       = new ManagerBatchItem();

                var result = _iSettingManager.GetSettingsByContext(tenantId, SettingContextTypeEnum.EMAIL);
                if (result != null)
                {
                    EmailSenderOptions options = Newtonsoft.Json.JsonConvert.DeserializeObject <EmailSenderOptions>(result.Content);
                    //Get Batch Item
                    var allBatchItems = _managerBatchItem.GetBatchItems(tenantId, new Guid(batchType.InternalId.Value), (batchType.ItemRetryCount.Value.Length > 0 ? (int?)Int32.Parse(batchType.ItemRetryCount.Value) : (int?)null));
                    foreach (var allBatchItem in allBatchItems)
                    {
                        try
                        {
                            var queryContext = new QueryContext {
                                Fields = "Body,Sender,Recipient,Subject,Id"
                            };
                            DataTable templatedt = _queryManager.GetResultById(tenantId, "email", allBatchItem.ReferenceId, queryContext);

                            _managerBatchItem.BatchItemUpdateStartTime(tenantId, allBatchItem.BatchItemId);
                            var email = EntityMapper <Email> .Mapper(templatedt);

                            SendEmail(tenantId, allBatchItem, email.Recipient.Value, email.Subject.Value, email.Body.Value, options);

                            //Update batch History
                            _managerBatchItem.BatchHistoryCreate(tenantId, new BatchItemHistory {
                                BatchHistoryId = Guid.NewGuid(),
                                BatchItemId    = allBatchItem.BatchItemId,
                                EntityId       = allBatchItem.EntityId,
                                ReferenceId    = allBatchItem.ReferenceId,
                                Status         = EmailEnum.Send,
                                RunTime        = allBatchItem.NextRunTime
                            });
                            //Update Email Status
                            _iEntityResourceManager.UpdateSpecificField(tenantId, "email", allBatchItem.ReferenceId, "Status", ((int)EmailEnum.Send).ToString());
                        }
                        catch (System.Exception ex)
                        {
                            _log.Error("An error has occurred while sending email", ex.Message);

                            //Update batch History
                            _managerBatchItem.BatchHistoryCreate(tenantId, new BatchItemHistory {
                                BatchHistoryId = Guid.NewGuid(),
                                BatchItemId    = allBatchItem.BatchItemId,
                                EntityId       = allBatchItem.EntityId,
                                ReferenceId    = allBatchItem.ReferenceId,
                                Status         = EmailEnum.Fail,
                                RunTime        = allBatchItem.NextRunTime,
                                FailedReason   = ex.Message
                            });
                            //Update Batch item status
                            _managerBatchItem.BatchItemUpdate(tenantId, (batchType.ItemRetryCount.Value.Length > 0 ? (int?)Int32.Parse(batchType.ItemRetryCount.Value) : (int?)null),
                                                              new BatchItem {
                                BatchItemId  = allBatchItem.BatchItemId,
                                Status       = EmailEnum.Fail,
                                FailedReason = ex.Message
                            });
                            //Update Email Status
                            _iEntityResourceManager.UpdateSpecificField(tenantId, "email", allBatchItem.ReferenceId, "Status", ((int)EmailEnum.Fail).ToString());
                            throw ex;
                        }

                        //Update Batch item status
                        _managerBatchItem.BatchItemUpdateStatus(tenantId, new BatchItem {
                            Status = EmailEnum.Send, BatchItemId = allBatchItem.BatchItemId
                        });
                    }
                }
                else
                {
                    _log.Error("Email gateway not configured");
                }
            }
            catch (System.Exception ex)
            {
                _log.Error("Email send failed", ex.Message);
            }
        }