Event Receiver stop working - sharepoint-2010

For some reason I was working on an event receiver when it stopped working. I am updating it and deploying from Visual Studio 2010 and it was previously working but it stopped when I was doing lookup fields. It is not working any more even if I remove the portion I just added. any ideas. thank you.
`/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
string fname = Convert.ToString(properties.AfterProperties["Title"]);
string Cdate = Convert.ToString(properties.AfterProperties["CDate"]).Substring(2, 2);
// ---- Lookup fields -----
String lookupZF = "Office";
String ZF = Convert.ToString(properties.ListItem[lookupZF]);
SPFieldLookupValue ZFValue = new SPFieldLookupValue(ZF);
// ------ End of lookup fields -----
string FName = fname + Cdate; // + ZFValue;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList CurrentList = web.Lists[properties.ListId];
SPListItem Litem = CurrentList.GetItemById(properties.ListItemId);
Litem["Description"] = "update working ...!";
Litem["Prop No."] = FName;
Litem.Update();
CurrentList.Update();
web.AllowUnsafeUpdates = false;
}
}
});
}`

I would suggest to check if the feature is activated in Manage site features after you deploy your solution.

I had to use dateTime then get the year. for some reason I was getting empty or null string that stopped the excution of the code. here is what worked:
DateTime Cdate = DateTime.Parse(properties.ListItem["Created"].ToString());
string SDate = Cdate.Year.ToString().Substring(2, 2);

Related

Index Out of Bound exception while rendering RDLC Reports in ASP.NET Core

My ASP.NET Core MVC project has several reports. To render the reports as PDF, I'm using AspNetCore.Reporting library.
This library works fine for a single report but due to some cache issues it throws an exception while generating another report. The solution I found on the internet was to run report generation as a new process but I don't know how to implement that.
I found the suggestion to use Tmds.ExecFunction to run report generation as a seperate process. But I dont know how to pass parameters to the function.
Here is my code:
string ReportName = "invoiceDine";
DataTable dt = new DataTable();
dt = GetInvoiceItems(invoiceFromDb.Id);
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("bParam", $"{invoiceFromDb.Id}");
param.Add("gParam", $"{salesOrderFromDb.Guests}");
param.Add("tParam", $"{invoiceFromDb.Table.Table}");
param.Add("dParam", $"{invoiceFromDb.Time}");
param.Add("totalP", $"{invoiceFromDb.SubTotal}");
param.Add("t1", $"{tax1}");
param.Add("t2", $"{tax2}");
param.Add("tA1", $"{tax1Amount}");
param.Add("tA2", $"{tax2Amount}");
param.Add("AT1", $"{totalAmountWithTax1}");
param.Add("AT2", $"{totalAmountWithTax2}");
param.Add("terminalParam", $"{terminalFromDb.Name}");
param.Add("addressParam", $"{t.Address}");
param.Add("serviceParam", "Service Charges of applicable on table of " + $"{personForServiceCharges}" + " & Above");
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
return File(result,"application/Pdf");
This is my version of the function:
``` public byte[] GenerateReport(string ReportName, Dictionary<string,string> Parameters,string DataSetName,DataTable DataSource )
{
string guID = Guid.NewGuid().ToString().Replace("-", "");
string fileDirPath = Assembly.GetExecutingAssembly().Location.Replace("POS_Website.dll", string.Empty);
string ReportfullPath = Path.Join(fileDirPath, "\\Reports");
string JsonfullPath = Path.Join(fileDirPath,"\\JsonFiles");
string rdlcFilePath = string.Format("{0}\\{1}.rdlc", ReportfullPath, ReportName);
string generatedFilePath = string.Format("{0}\\{1}.pdf", JsonfullPath, guID);
string jsonDataFilePath = string.Format("{0}\\{1}.json", JsonfullPath, guID);
File.WriteAllText(jsonDataFilePath, JsonConvert.SerializeObject(DataSource));
FunctionExecutor.Run((string[] args) =>
{
// 0 : Data file path - jsonDataFilePath
// 1 : Filename - generatedFilePath
// 2 : RDLCPath - rdlcFilePath
ReportResult result;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
LocalReport report = new LocalReport(args[2]);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(File.ReadAllText(args[0]));
report.AddDataSource(args[3], dt);
result = report.Execute(RenderType.Pdf, 1,Parameters);
using (var fs = new FileStream(args[1], FileMode.Create, FileAccess.Write))
{
fs.Write(result.MainStream);
}
}, new string[] {jsonDataFilePath, generatedFilePath, rdlcFilePath, DataSetName });
var memory = new MemoryStream();
using (var stream = new FileStream(Path.Combine("", generatedFilePath), FileMode.Open))
{
stream.CopyTo(memory);
}
File.Delete(generatedFilePath);
File.Delete(jsonDataFilePath);
memory.Position = 0;
return memory.ToArray();
}
But it throws exception "Field marshaling is not supported by ExecFunction" on line:
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
No Need to run report generation as a seperate process. Just Dont Pass extension as 1
in:
var result = localReport.Execute(RenderType.Pdf, 1, param);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);

Create Defect in Rally using REST API and C#

I am trying to programatically create a defect in Rally using C#. Below is my code and errors i am getting is
Error in creating defect!!!
Cannot parse object reference from "Unspecified"
Code:
RallyRestApi restApi;
restApi = new RallyRestApi(webServiceVersion: "v2.0");
//after successful authentication...
String workspaceRef = "/workspace/12345";
String projectRef = "/project/78321";
DynamicJsonObject badDefect = new DynamicJsonObject();
newDefect["Name"] = "Defect " + DateTime.Now;
newDefect["Project"] = projectRef ;
newDefect["Environment"] = "test branch";
newDefect["c_DefectSourceNEW"] = "old";
newDefect["Severity"] = "minor";
newDefect["Release"] = "Unspecificed";
CreateResult createResult = restApi.Create("Defect", newDefect);
if (createResult.Success == true)
{
Console.WriteLine("Defect created Successfully!!!");
}
else
{
Console.WriteLine("Error in creating defect!!!");
}
foreach (string s in createResult.Errors)
{
Console.WriteLine(s);
}
Can some one suggest what i might be doing incorrectly and in general the correct way to sepcify "Release" value for a defect???
All object relationships in wsapi are represented by refs. So you just need to set the value as its ref rather than its name, much like you're already doing with workspace and project.
Thanks Kyle for inputs. Since the Release ID was mandatory i solved by below for Release Input:
Request reRequest = new Request("Release");
reRequest.Workspace = workspaceRef;
reRequest.Query = new Query("Project", Query.Operator.Equals, projectRef);
QueryResult queryResult = restApi.Query(reRequest);
string reprojectRef = null;
foreach (DynamicJsonObject result in queryResult.Results)
{
reprojectRef = result["_ref"];
Console.WriteLine(reprojectRef);
Console.WriteLine("Name: " + result["Name"]);
if (result["Name"] == "MyReleaseName")
{
newDefect["Release"] = result["_ref"];
}
}

Web Api Service

I am Consuming web api service from one project (project1) to another project (project2) but when i try to get the response from project2 to project1 with this code
using (var client = new WebClient())
{
string json = URL;
Var jdownload = client.DownloadString(json);
}
It's adding back slashed into "jdownload" Var please guide me how i can get that response without that backslashes
i.e
“servicefor” = “GetData”,
“settings” = {
\"stringname\":5,
\"url\":\"null",
\"services\":\"GetSet\",
\"interval\":2.0,
\"alldatacontains\":200,
\"netamountname\":\"BulkFetch\"
}
I got the solution how can i get the Clean Jason
public JObject GetData(string dataO)
{
var data = MethodToGetData(dataO);
JObject pobj = JObject.FromObject(new
{
type = "stgdats",
val = "val",
d_id = id,
sat = data
}
);
return pobj;
}

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}

WCF- Large Data [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a WCF Web Service with basicHTTPBinding , the server side the transfer mode is streamedRequest as the client will be sending us large file in the form of memory stream.
But on client side when i use transfer mode as streamedRequest its giving me a this errro
"The remote server returned an error: (400) Bad Request"
And when i look in to trace information , i see this as the error message
Exception: There is a problem with the XML that was received from the network. See inner exception for more details.
InnerException: The body of the message cannot be read because it is empty.
I am able to send up to 5MB of data using trasfermode as buffered , but it will effect the performance of my web service in the long run , if there are many clients who are trying to access the service in buffered transfer mode.
SmartConnect.Service1Client Serv = new SmartConnectClient.SmartConnect.Service1Client();
SmartConnect.OrderCertMailResponse OrderCert = new SmartConnectClient.SmartConnect.OrderCertMailResponse();
OrderCert.UserID = "abcd";
OrderCert.Password = "7a80f6623";
OrderCert.SoftwareKey = "90af1";
string applicationDirectory = #"\\inid\utty\Bran";
byte[] CertMail = File.ReadAllBytes(applicationDirectory + #"\5mb_test.zip");
MemoryStream str = new MemoryStream(CertMail);
//OrderCert.Color = true;
//OrderCert.Duplex = false;
//OrderCert.FirstClass = true;
//OrderCert.File = str;
//OrderCert.ReturnAddress1 = "Test123";
//OrderCert.ReturnAddress2 = "Test123";
//OrderCert.ReturnAddress3 = "Test123";
//OrderCert.ReturnAddress4 = "Test123";
OrderCert.File = str;
//string OrderNumber = "";
//string Password = OrderCert.Password;
//int ReturnCode = 0;
//string ReturnMessage = "";
//string SoftwareKey = OrderCert.SoftwareKey;
//string UserID = OrderCert.UserID;
//OrderCert.File = str;
MemoryStream FileStr = str;
Serv.OrderCertMail(OrderCert);
// Serv.OrderCertMail(ref OrderNumber, ref Password, ref ReturnCode, ref ReturnMessage, ref SoftwareKey, ref UserID, ref FileStr );
lblON.Text = OrderCert.OrderNumber;
Serv.Close();
// My Web Service - Service Contract
[OperationContract]
OrderCertMailResponse OrderCertMail(OrderCertMailResponse OrderCertMail);
[MessageContract]
public class OrderCertMailResponse
{
string userID = "";
string password = "";
string softwareID = "";
MemoryStream file = null;
//MemoryStream str = null;
[MessageHeader]
//[DataMember]
public string UserID
{
get { return userID; }
set { userID = value; }
}
[MessageHeader]
//[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[MessageHeader]
//[DataMember]
public string SoftwareKey
{
get { return softwareID; }
set { softwareID = value; }
}
[MessageBodyMember]
// [DataMember]
public MemoryStream File
{
get { return file; }
set { file = value; }
}
[MessageHeader]
//[DataMember]
public string ReturnMessage;
[MessageHeader]
//[DataMember]
public int ReturnCode;
[MessageHeader]
public string OrderNumber;
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Service1 : IService1
{
public OrderCertMailResponse OrderCertMail(OrderCertMailResponse OrderCertMail)
{
OrderService CertOrder = new OrderService();
ClientUserInfo Info = new ClientUserInfo();
ControlFileInfo Control = new ControlFileInfo();
//Info.Password = "f2496623"; // hard coded password for development testing purposes
//Info.SoftwareKey = "6dbb71"; // hard coded software key this is a developement software key
//Info.UserName = "sdfs"; // hard coded UserID - for testing
Info.UserName = OrderCertMail.UserID.ToString();
Info.Password = OrderCertMail.Password.ToString();
Info.SoftwareKey = OrderCertMail.SoftwareKey.ToString();
//Control.ReturnAddress1 = OrderCertMail.ReturnAddress1;
//Control.ReturnAddress2 = OrderCertMail.ReturnAddress2;
//Control.ReturnAddress3 = OrderCertMail.ReturnAddress3;
//Control.ReturnAddress4 = OrderCertMail.ReturnAddress4;
//Control.CertMailFirstClass = OrderCertMail.FirstClass;
//Control.CertMailColor = OrderCertMail.Color;
//Control.CertMailDuplex = OrderCertMail.Duplex;
//byte[] CertFile = new byte[0];
//byte[] CertFile = null;
//string applicationDirectory = #"\\inid\utility\Bryan";
// byte[] CertMailFile = File.ReadAllBytes(applicationDirectory + #"\3mb_test.zip");
//MemoryStream str = new MemoryStream(CertMailFile);
OrderCertMailResponseClass OrderCertResponse = CertOrder.OrderCertmail(Info,Control,OrderCertMail.File);
OrderCertMail.ReturnMessage = OrderCertResponse.ReturnMessage.ToString();
OrderCertMail.ReturnCode = Convert.ToInt32(OrderCertResponse.ReturnCode.ToString());
OrderCertMail.OrderNumber = OrderCertResponse.OrderNumber;
return OrderCertMail;
}
Below are my new operation contract which takes only datastream as a parameter
[OperationContract]
SmartStream SendStream(MemoryStream DataStream);
public SmartStream SendStream(MemoryStream DataStream)
{
OrderService CertOrder = new OrderService();
ClientUserInfo Info = new ClientUserInfo();
ControlFileInfo Control = new ControlFileInfo();
MemoryStream serverStream = null;
Info.Password = "78f24dsfsdf96623";
Info.SoftwareKey = "dfs6dbb71";
Info.UserName = "ssfsdf";
using (serverStream = new MemoryStream(100))
{
int count = 0;
const int buffLen = 4096;
byte[] buf = new byte[buffLen];
while ((count = CertFile.Read(buf, 0, buffLen)) > 0)
{
serverStream.Write(buf, 0, count);
}
CertFile.Close();
serverStream.Close();
return null;
}
My client method to access
protected void Page_Load(object sender, EventArgs e)
{
SmartConnect.Service1Client Serv = new
SmartConnectClient.SmartConnect.Service1Client();
string applicationDirectory = #"\\intrepid\utility\Bryan";
byte[] CertMail = File.ReadAllBytes(applicationDirectory + #"\100mb_test.zip");
MemoryStream str = new MemoryStream(CertMail);
SmartConnectClient.SmartConnect.SendStreamRequest request =
new SmartConnectClient.SmartConnect.SendStreamRequest();
SmartConnectClient.SmartConnect.SmartStream SmartStr =
new SmartConnectClient.SmartConnect.SmartStream();
request.DataStream = str;
SmartConnectClient.SmartConnect.SendStreamResponse response = Serv.SendStream(request);
}
Pinu, I still think you're probably not doing the service contract right for WCF streaming. See the MSDN docs on WCF Streaming - especially this section on restrictions:
Restrictions on Streamed Transfers
Using the streamed transfer mode
causes the run time to enforce
additional restrictions.
Operations that occur across a
streamed transport can have a contract
with at most one input or output
parameter. That parameter corresponds
to the entire body of the message and
must be a Message, a derived type of
Stream, or an IXmlSerializable
implementation. Having a return value
for an operation is equivalent to
having an output parameter.
From your code posted, I'm still under the impression you're trying to mix both buffered and streamed transfers.
If you want to have real streaming, your service contract must look something like:
[ServiceContract(Namespace=".....")]
interface IUploadFileService
{
[OperationContract]
UploadResponse UploadFile(Stream file);
}
That's about all you can have in your service contract for that service method.
Also have a look at some really good blog posts on streaming here and here.
#Marc - Thank you so much for all the your help. It helped me fix many of the problems of my service.
The web service started working when I ran it on local IIS on my machine , it was throwing all those errors when I was running on the Visual Studio development server. I could not figure why it is so , why it did not run on Visual studio development server.