Closing Case in Acumatica through API - acumatica

I want to close the case in Partners Portal remotely using Web API, whenever I close the case in my (client) side. I was able to implement the code but ran into below issue.
It is changing the status and resolution of the case in Partners Portal but Close Case button is enabled and it is visible in My Open Case bucket. Please let me know if I can close the case remotely using Web API or if I am missing anything.
protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
var caseRow = (CRCase)e.Row;
if (caseRow != null)
{
if (caseRow.Status == "C") // Closed
{
string cloud9CaseCD = null;
cloud9CaseCD = CRCaseForCreate.Current.CaseCD;
string acumaticaCaseCD = string.Empty;
CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
if (aCCaseNoAttribute != null)
{
acumaticaCaseCD = aCCaseNoAttribute.Value;
if(!string.IsNullOrEmpty(acumaticaCaseCD))
{
SP203000WS.Screen context = new SP203000WS.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "https://sso.acumatica.com/Soap/SP203000.asmx";
PartnerPortalCreds loginCreds = GetCreds();
string username = loginCreds.PARTPRTUSE;
string password = loginCreds.PARTPRTPAS;
SP203000WS.LoginResult result = context.Login(username, password);
SP203000WS.Content CR306000 = context.GetSchema();
context.Clear();
SP203000WS.Content[] CR306000Content = context.Submit
(
new SP203000WS.Command[]
{
new SP203000WS.Value
{
Value = acumaticaCaseCD,
LinkedCommand = CR306000.Case.CaseID
},
new SP203000WS.Value
{
Value = "C",
LinkedCommand = new SP203000WS.Field { FieldName="Status", ObjectName="Case"}
},
new SP203000WS.Value
{
Value = "RD",
LinkedCommand = new SP203000WS.Field { FieldName="Resolution", ObjectName="Case"}
},
CR306000.Actions.Submit,
CR306000.Case.CaseID
}
);
context.Logout();
}
}
}
}
}
Tried below code using CloseCase Action: -
protected virtual void CRCase_RowPersisting(PXCache cache, PXRowPersistingEventArgs e)
{
var caseRow = (CRCase)e.Row;
if (caseRow != null)
{
if (caseRow.Status == "C") // Closed
{
string cloud9CaseCD = null;
cloud9CaseCD = CRCaseForCreate.Current.CaseCD;
string acumaticaCaseCD = string.Empty;
CSAnswers aCCaseNoAttribute = PXSelect<CSAnswers,
Where<CSAnswers.refNoteID, Equal<Required<CSAnswers.refNoteID>>,
And<CSAnswers.attributeID, Equal<Required<CSAnswers.attributeID>>>>>.Select(new PXGraph(), CRCaseForCreate.Current.NoteID, "ACCASENO");
if (aCCaseNoAttribute != null)
{
acumaticaCaseCD = aCCaseNoAttribute.Value;
if (!string.IsNullOrEmpty(acumaticaCaseCD))
{
SP203010WS.Screen context = new SP203010WS.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "https://sso.acumatica.com/Soap/SP203010.asmx";
PartnerPortalCreds loginCreds = GetCreds();
string username = loginCreds.PARTPRTUSE;
string password = loginCreds.PARTPRTPAS;
SP203010WS.LoginResult result = context.Login(username, password);
SP203010WS.Content CR306000 = context.GetSchema();
context.Clear();
var commands1 = new SP203010WS.Command[]
{
new SP203010WS.Value
{
Value = acumaticaCaseCD,
LinkedCommand = CR306000.Case.CaseID
},
new SP203010WS.Value
{
Value = "Yes",
LinkedCommand = CR306000.Case.ServiceCommands.DialogAnswer, Commit = true
},
CR306000.Actions.CloseCase
};
var data = context.Submit(commands1);
context.Logout();
}
}
}
}
}
In the below image you can see that the case is already closed but Close Case menu button is still visible.
Close Case Confirmation Dialogbox on Partners Portal. How should I answer this dialogbox programatically while closing the case using Web API.

Have you tried to invoke Close action via Web API instead of changing values of the Status and Resolution fields? As far as I know, Close button on the Partner Portal updates support case Status to Open and Reason to Pending Closure. Then it's up to support personnel to manually close the case.

Finally found the solution. Updated the code for CloseCase (second code snippet). This will mark the case as Pending Closure in Partners Portal.

Related

Add an additional line on the grid

I am looking for help, I hope I can solve this problem.
I've created a new screen and I'm filtering all the Revalue Accounts information.
With this screen, what I want to do is insert and at the same time add an additional new line within the grid.
Here is my new created screen and the button that inserts GLTran
I am attaching an image where I want the line to be added at insert time
Here I share code that I have and it does not work for the additional line.
private void CreateDNGL(Batch batch)
{
var graph = PXGraph.CreateInstance<JournalEntry>();
if (graph.BatchModule.Current == null)
{
Batch cmbatch = new Batch();
cmbatch.BranchID = batch.BranchID;
cmbatch.Module = batch.Module;
cmbatch.Status = "U";
cmbatch.AutoReverse = true;
cmbatch.Released = true;
cmbatch.Hold = false;
cmbatch.CuryDebitTotal = batch.CuryDebitTotal;
cmbatch.CuryCreditTotal = batch.CuryCreditTotal;
cmbatch.FinPeriodID = batch.FinPeriodID;
cmbatch.CuryID = batch.CuryID;
cmbatch.CuryInfoID = batch.CuryInfoID;
cmbatch.DebitTotal = batch.DebitTotal;
cmbatch.CreditTotal = batch.CreditTotal;
cmbatch.Description = "Head new insert";
cmbatch = graph.BatchModule.Insert(cmbatch);
}
foreach (GLTran item in PXSelect<GLTran,
Where<GLTran.module, Equal<Required<GLTran.module>>,
And<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>>>>.Select(this, batch.Module, batch.BatchNbr))
{
GLTran tran = new GLTran();
tran.SummPost = item.SummPost;
tran.ZeroPost = false;
tran.DebitAmt = item.DebitAmt;
tran.CreditAmt = item.CreditAmt;
tran.CuryDebitAmt = item.CuryDebitAmt;
tran.CuryCreditAmt = item.CuryCreditAmt;
tran.AccountID = item.AccountID;
tran.SubID = item.SubID;
tran.LineNbr = item.LineNbr;
tran.LedgerID = item.LedgerID;
tran.TranType = item.TranType;
tran.TranClass = item.TranClass;
tran.RefNbr = string.Empty;
tran.FinPeriodID = item.FinPeriodID;
tran.TranDesc = "Test detail";
tran.Released = true;
tran.ReferenceID = item.ReferenceID;
tran = graph.GLTranModuleBatNbr.Insert(tran);
Account account = PXSelect<Account, Where<Account.accountID,
Equal<Required<Account.accountID>>>>.Select(graph, item.AccountID);
xLocEquivalAcct equivalAcct = PXSelect<xLocEquivalAcct, Where<xLocEquivalAcct.acctCD,
Equal<Required<xLocEquivalAcct.acctCD>>>>.Select(graph, account.AccountCD);
if (equivalAcct != null)
{
/*here is added for an additional line*/
var glTran = graph.GLTranModuleBatNbr.Insert();
graph.GLTranModuleBatNbr.SetValueExt<GLTran.accountID>(glTran, 343567);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.subID>(glTran, 281);
glTran.TranDesc = "add extra line";
if (item.DebitAmt != 0m && item.CreditAmt == 0m)
{
if (batch.Module == BatchModule.CM)
{
graph.GLTranModuleBatNbr.SetValueExt<GLTran.curyDebitAmt>(glTran, item.CuryDebitAmt);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.debitAmt>(glTran, item.DebitAmt);
}
}
if (item.CreditAmt != 0m && item.DebitAmt == 0m)
{
if (batch.Module == BatchModule.CM)
{
graph.GLTranModuleBatNbr.SetValueExt<GLTran.curyCreditAmt>(glTran, item.CuryCreditAmt);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.creditAmt>(glTran, item.CreditAmt);
}
}
glTran = graph.GLTranModuleBatNbr.Update(glTran);
}
}
graph.Save.Press();
}
I hope I was clear with my question.
This code will create a copy of the originating batch and insert additional lines.
#Warning Your original code was attempting to create a batch that was already released but unposted. I can update my answer to match your requirement but this will break Acumatica work-flow.
Please find code example below :
public class JournalEntryExtension : PXGraphExtension<JournalEntry>
{
public PXAction<Batch> CopyCreate;
//CommitChanges being set to false allows the graph to not be considered dirty when there are errors that we manually show on screen. Case #207998
[PXButton(CommitChanges = false)]
[PXUIField(DisplayName = "Copy Create", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Update, Enabled = true)]
protected virtual IEnumerable copyCreate(PXAdapter pxAdapter)
{
if (Base.BatchModule.Current != null)
{
if (Base.IsDirty)
{
Base.BatchModule.Ask("You must discard your unsaved changes to be able to press this button.", MessageButtons.OK);
}
else
{
Batch batch = Base.BatchModule.Current;
PXLongOperation.StartOperation(this, () => CreateDNGL(batch));
}
}
return pxAdapter.Get();
}
private static void CreateDNGL(Batch batch)
{
JournalEntry graph = PXGraph.CreateInstance<JournalEntry>();
Batch newBatch = PXCache<Batch>.CreateCopy(batch);
newBatch.NoteID = null;
newBatch.Description = "Test header";
newBatch = graph.BatchModule.Insert(newBatch);
GLTran newTran;
foreach (GLTran tran in PXSelectReadonly<GLTran,
Where<GLTran.module, Equal<Required<GLTran.module>>,
And<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>>>>.Select(graph, batch.Module, batch.BatchNbr))
{
newTran = PXCache<GLTran>.CreateCopy(tran);
newTran.Module = null;
newTran.BatchNbr = null;
newTran.NoteID = null;
newTran.TranDesc = "Test detail";
newTran = graph.GLTranModuleBatNbr.Insert(newTran);
}
if (true)
{
newTran = graph.GLTranModuleBatNbr.Insert();
newTran.AccountID = 1190;
newTran.SubID = 467;
newTran.CuryDebitAmt = 1000;
newTran.TranDesc = "Additional Line 1";
newTran = graph.GLTranModuleBatNbr.Update(newTran);
newTran = graph.GLTranModuleBatNbr.Insert();
newTran.AccountID = 1190;
newTran.SubID = 467;
newTran.CuryCreditAmt = 1000;
newTran.TranDesc = "Additional Line 2";
newTran = graph.GLTranModuleBatNbr.Update(newTran);
}
graph.Save.Press();
}
}
Original Batch :
New Batch :

Acumatica API Error when creating a Inventory Receipts API calls

Good day
I am creating a SOAP contract base connection to Acumatica.
I am getting an error: "System.ArgumentNullException: Value cannot be null."
I am not sure why I am getting the error.
Here is my code
using (var soapClient = new DefaultSoapClient())
{
try
{
soapClient.Login();
InventoryReceipt NewinventoryReceipt = new InventoryReceipt
{
ReferenceNbr = new StringValue { Value = "<NEW>" },
Hold = new BooleanValue { Value = true },
Date = new DateTimeValue { Value = DateTime.Now },
PostPeriod = new StringValue { Value = DateTime.Now.ToString("DD-yyyy") },
TransferNbr = new StringValue { Value = "" },
//External Ref
Description = new StringValue { Value = "" },
Details = new InventoryReceiptDetail[]
{
new InventoryReceiptDetail
{
//branch
InventoryID = new StringValue{Value = "NIS777"},
WarehouseID = new StringValue{Value = "FBTZEST"},
Location = new StringValue {Value = "BULK"},
Qty = new DecimalValue{Value = 1},
UOM = new StringValue{Value = "PALLET"},
UnitCost = new DecimalValue{Value = 91},
ExtCost = new DecimalValue{Value = 91},
LotSerialNbr = new StringValue{Value = "PLN12345"},
ExpirationDate = new DateTimeValue{Value = DateTime.Now},
// ReasonCode
Description = new StringValue{Value = ""}
}
},
};
InventoryReceipt putInventoryReceipt = (InventoryReceipt)soapClient.Put(NewinventoryReceipt);
}
catch (Exception ex)
{
soapClient.Logout();
throw;
}
finally
{
soapClient.Logout();
}
soapClient.Logout();
}
Console.ReadLine();
}
Is there any way to see what is null or what I am missing to post this data?
Have you tried manually entering the data into the UI? The Validation on the web service should be the same as the UI, so you might get more info from the UI. You have a lot of dependent values here since you're referencing a specific Lot perhaps a value is missing. Other than that, you might try adding Project = X.

Inserting new Activity for Case Screen by code

I am trying to insert a new Activity for Case. The code which I have written executes without any error but it even does not inserts any Activity. Let me know if I am missing anything.
Here is the code
CRActivity actiCloud9 = new CRActivity();
actiCloud9.Type = "N"; // Note
actiCloud9.Subject = current.Summary;
actiCloud9.Body = current.Description;
actiCloud9.UIStatus = current.Status;
actiCloud9.StartDate = current.StartDate;
actiCloud9.IsPrivate = true; // current.IsInternal;
actiCloud9.RefNoteID = Base.CaseCurrent.Current.NoteID;
Base.Activities.Cache.Insert(actiCloud9);
Try this.
[PXOverride]
public void Persist(Action del)
{
if ((Base.Case.Cache.GetStatus(Base.Case.Current) == PXEntryStatus.Inserted || Base.Case.Cache.GetStatus(Base.Case.Current) == PXEntryStatus.Updated))
{
CRActivityMaint objGraph = PXGraph.CreateInstance<CRActivityMaint>();
CRActivity actiCloud9 = new CRActivity();
actiCloud9.Type = "N"; // Note
actiCloud9.Subject = "Subject";
actiCloud9.Body = "Body";
actiCloud9.RefNoteID = Base.CaseCurrent.Current.NoteID;
objGraph.Activities.Cache.Insert(actiCloud9);
objGraph.Actions.PressSave();
}
del();
}

NetSuite SuiteTalk API - Get Inventory Details

I'm using the SuiteTalk (API) service for NetSuite to retrieve a list of Assemblies. I need to load the InventoryDetails fields on the results to view the serial/lot numbers assigned to the items. This is the current code that I'm using, but the results still show those fields to come back as NULL, although I can see the other fields for the AssemblyBuild object. How do I get the inventory details (serials/lot#'s) to return on a transaction search?
public static List<AssemblyBuildResult> Get()
{
var listAssemblyBuilds = new List<AssemblyBuildResult>();
var service = Service.Context();
var ts = new TransactionSearch();
var tsb = new TransactionSearchBasic();
var sfType = new SearchEnumMultiSelectField
{
#operator = SearchEnumMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new string[] { "_assemblyBuild" }
};
tsb.type = sfType;
ts.basic = tsb;
ts.inventoryDetailJoin = new InventoryDetailSearchBasic();
// perform the search
var response = service.search(ts);
response.pageSizeSpecified = true;
// Process response
if (response.status.isSuccess)
{
// Process the records returned in the response
// Get more records with pagination
if (response.totalRecords > 0)
{
for (var x = 1; x <= response.totalPages; x++)
{
var records = response.recordList;
foreach (var t in records)
{
var ab = (AssemblyBuild) t;
listAssemblyBuilds.Add(GetAssemblyBuildsResult(ab));
}
if (response.pageIndex < response.totalPages)
{
response = service.searchMoreWithId(response.searchId, x + 1);
}
}
}
}
// Parse and return NetSuite WorkOrder into assembly WorkOrderResult list
return listAssemblyBuilds;
}
After much pain and suffering, I was able to solve this problem with the following code:
/// <summary>
/// Returns List of AssemblyBuilds from NetSuite
/// </summary>
/// <returns></returns>
public static List<AssemblyBuildResult> Get(string id = "", bool getDetails = false)
{
// Object to populate and return results
var listAssemblyBuilds = new List<AssemblyBuildResult>();
// Initiate Service and SavedSearch (TransactionSearchAdvanced)
var service = Service.Context();
var tsa = new TransactionSearchAdvanced
{
savedSearchScriptId = "customsearch_web_assemblysearchmainlist"
};
// Filter by ID if specified
if (id != "")
{
tsa.criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
internalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new[] {
new RecordRef() {
type = RecordType.assemblyBuild,
typeSpecified = true,
internalId = id
}
}
}
}
};
}
// Construct custom columns to return
var tsr = new TransactionSearchRow();
var tsrb = new TransactionSearchRowBasic();
var orderIdCols = new SearchColumnSelectField[1];
var orderIdCol = new SearchColumnSelectField();
orderIdCols[0] = orderIdCol;
tsrb.internalId = orderIdCols;
var tranDateCols = new SearchColumnDateField[1];
var tranDateCol = new SearchColumnDateField();
tranDateCols[0] = tranDateCol;
tsrb.tranDate = tranDateCols;
var serialNumberCols = new SearchColumnStringField[1];
var serialNumberCol = new SearchColumnStringField();
serialNumberCols[0] = serialNumberCol;
tsrb.serialNumbers = serialNumberCols;
// Perform the Search
tsr.basic = tsrb;
tsa.columns = tsr;
var response = service.search(tsa);
// Process response
if (response.status.isSuccess)
{
var searchRows = response.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
foreach (SearchRow t in searchRows)
{
var transactionRow = (TransactionSearchRow)t;
listAssemblyBuilds.Add(GetAssemblyBuildsResult(transactionRow, getDetails));
}
}
}
// Parse and return NetSuite WorkOrder into assembly WorkOrderResult list
return listAssemblyBuilds;
}
private static string GetAssemblyBuildLotNumbers(string id)
{
var service = Service.Context();
var serialNumbers = "";
var tsa = new TransactionSearchAdvanced
{
savedSearchScriptId = "customsearch_web_assemblysearchlineitems"
};
service.searchPreferences = new SearchPreferences { bodyFieldsOnly = false };
tsa.criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
internalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new[] {
new RecordRef() {
type = RecordType.assemblyBuild,
typeSpecified = true,
internalId = id
}
}
}
}
};
// Construct custom columns to return
var tsr = new TransactionSearchRow();
var tsrb = new TransactionSearchRowBasic();
var orderIdCols = new SearchColumnSelectField[1];
var orderIdCol = new SearchColumnSelectField();
orderIdCols[0] = orderIdCol;
tsrb.internalId = orderIdCols;
var serialNumberCols = new SearchColumnStringField[1];
var serialNumberCol = new SearchColumnStringField();
serialNumberCols[0] = serialNumberCol;
tsrb.serialNumbers = serialNumberCols;
tsr.basic = tsrb;
tsa.columns = tsr;
var response = service.search(tsa);
if (response.status.isSuccess)
{
var searchRows = response.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
foreach (SearchRow t in searchRows)
{
var transactionRow = (TransactionSearchRow)t;
if (transactionRow.basic.serialNumbers != null)
{
return transactionRow.basic.serialNumbers[0].searchValue;
}
}
}
}
return serialNumbers;
}
private static AssemblyBuildResult GetAssemblyBuildsResult(TransactionSearchRow tsr, bool getDetails)
{
if (tsr != null)
{
var assemblyInfo = new AssemblyBuildResult
{
NetSuiteId = tsr.basic.internalId[0].searchValue.internalId,
ManufacturedDate = tsr.basic.tranDate[0].searchValue,
SerialNumbers = tsr.basic.serialNumbers[0].searchValue
};
// If selected, this will do additional NetSuite queries to get detailed data (slower)
if (getDetails)
{
// Look up Lot Number
assemblyInfo.LotNumber = GetAssemblyBuildLotNumbers(tsr.basic.internalId[0].searchValue.internalId);
}
return assemblyInfo;
}
return null;
}
What I learned about pulling data from NetSuite:
Using SavedSearches is the best method to pull data that doesn't automatically come through in the API objects
It is barely supported
Don't specify an ID on the SavedSearch, specify a criteria in the TransactionSearch to get one record
You will need to specify which columns to actually pull down. NetSuite doesn't just send you the data from a SavedSearch automatically
You cannot view data in a SavedSearch that contains a Grouping
In the Saved Search, use the Criteria Main Line = true/false to read data from the main record (top of UI screen), and line items (bottom of screen)

I use sqldependency AND signalR AND thread but it goes on infinite loop

I use sqldependency AND signalR AND thread but it goes on infinite loop
combine BackgroundWorker in global.aspx and sqldependency and signalR
I dont know about problem please help me.
void Application_Start(object sender, EventArgs e)
{
//var session = HttpContext.Current.Session;
//if (session != null && HttpContext.Current != null)
//{
try
{
CSASPNETBackgroundWorker.BackgroundWorker worker = new CSASPNETBackgroundWorker.BackgroundWorker();
worker.DoWork += new CSASPNETBackgroundWorker.BackgroundWorker.DoWorkEventHandler(worker_DoWork);
worker.RunWorker(null);
// This Background Worker is Applicatoin Level,
// so it will keep working and it is shared by all users.
Application["worker"] = worker;
// Code that runs on application startup
}
catch { }
// }
System.Data.SqlClient.SqlDependency.Start(connectionstring);
}
string user_id;
void worker_DoWork(ref int progress,
ref object _result, params object[] arguments)
{
// Do the operation every 1 second wihout the end.
while (true)
{
Random rand = new Random();
int randnum = rand.Next(5000, 20000);
Thread.Sleep(randnum);
// This statement will run every 1 second.
// string user_id = "";
// if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
// user_id = "22";// HttpContext.Current.Session["userId"].ToString();
user_id = ConfigurationManager.AppSettings["session_user_id"].ToString();
updatealarm(user_id);
}
// Other logic which you want it to keep running.
// You can do some scheduled tasks here by checking DateTime.Now.
}
}
AND
public class AlarmInfoRepository {
string connectionstr = ConfigurationManager.ConnectionStrings["officeConnectionString"].ConnectionString;
public IEnumerable GetData(string user_id)
{
using (SqlConnection connection = new SqlConnection(connectionstr))
{
//PersianCalendar jc = new PersianCalendar();
//string todayStr = jc.GetYear(DateTime.Now).ToString("0000") + "/" + jc.GetMonth(DateTime.Now).ToString("00") + "/" +
// jc.GetDayOfMonth(DateTime.Now).ToString("00");
//string timeStr = String.Format("{0:00}:{1:00}:{2:00}", jc.GetHour(DateTime.Now.AddSeconds(10)), jc.GetMinute(DateTime.Now.AddSeconds(10)), jc.GetSecond(DateTime.Now.AddSeconds(10)));
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT dbo.[web_alarmkartable].[id],dbo.[web_alarmkartable].peygir_id,dbo.[web_alarmkartable].user_id,
dbo.[web_alarmkartable].[content],dbo.[web_alarmkartable].[latestcreate_date],dbo.[web_alarmkartable].[latestcreate_time],
dbo.[web_alarmkartable].[firstcreate_date],dbo.[web_alarmkartable].[firstcreate_time],dbo.[web_alarmkartable].[duration],
dbo.[web_alarmkartable].[periodtype_id],dbo.[web_alarmkartable].[period],ISNULL(dbo.[web_alarmkartable].[color],'') AS color,dbo.[web_alarmkartable].id_tel FROM dbo.[web_alarmkartable] where dbo.[web_alarmkartable].content !='' AND dbo.[web_alarmkartable].content IS NOT NULL
AND (dbo.[web_alarmkartable].seen IS NULL OR dbo.[web_alarmkartable].seen =0) AND (dbo.[web_alarmkartable].expier IS NULL OR dbo.[web_alarmkartable].expier =0 )
AND (dbo.[web_alarmkartable].del=0 OR dbo.[web_alarmkartable].del IS NULL) AND dbo.[web_alarmkartable].user_id=" + user_id, connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new AlarmInfo()
{
id = x.GetInt32(0),
peygir_id = x.GetInt32(1),
user_id = x.GetInt32(2),
content = x.GetString(3),
latestcreate_date = x.GetString(4),
latestcreate_time = x.GetString(5),
firstcreate_date = x.GetString(6),
firstcreate_time = x.GetString(7),
duration = x.GetDecimal(8),
periodtype_id = x.GetInt32(9),
period = x.GetDecimal(10),
color = x.GetString(11),
id_tel = x.GetInt32(12)
}).ToList();
}
//if (connection.State == ConnectionState.Open)
// connection.Close();
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if ((e.Info.ToString() == "Insert" || e.Info.ToString() == "Update") && e.Type == SqlNotificationType.Change)
AlermHub.Show(e.Info.ToString());
}
}
AND

Resources