How to update textboxes' values in a specific form on Crm 4.0? - dynamics-crm-4

I want to update my account's datas.How can I access and update it ?
I can create a new account using this code but also i want to update :
private static CrmService ConnectToCrm()
{
CrmService service = new CrmService();
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "crm";
service.Url = "http://192.168.1.23:5555/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
return service;
}
protected void btnUpdateAccount_Click(object sender, EventArgs e)
{
try
{
CrmService MyService = ConnectToCrm();
DynamicEntity leadEntity = new DynamicEntity();
leadEntity.Name = EntityName.lead.ToString();
ArrayList arrProps = new ArrayList();
if (txtName.Text != string.Empty)
{
StringProperty firstname = new StringProperty();
firstname.Name = "firstname";
firstname.Value = txtName.Text;
arrProps.Add(firstname);
}
if (txtSurname.Text != string.Empty)
{
StringProperty lastname = new StringProperty();
lastname.Name = "lastname";
lastname.Value = txtSurname.Text;
arrProps.Add(lastname);
}
if (txtMail.Text != string.Empty)
{
StringProperty mail = new StringProperty();
mail.Name = "emailaddress1";
mail.Value = txtMail.Text;
arrProps.Add(mail);
}
if (txtState.Text != string.Empty)
{
StringProperty state = new StringProperty();
state.Name = "address1_stateorprovince";
state.Value = txtState.Text;
arrProps.Add(state);
}
leadEntity.Properties = (Property[])arrProps.ToArray(typeof(Property));
MyService.Create(leadEntity);
}

Updates work very similar to Creates. Just make sure that the DynamicEntity has the GUID and entity name of the record you want to update and replace
MyService.Create(leadEntity);
with
MyService.Update(LeadEntity);

Related

CREATE statement fails in ASP.NET MVC

My create statement could not work suddenly and it goes straight to an error message (Account cannot be created). I am not sure where I went wrong as I did not make any modification to it at all. In total, I have encountered this problem THRICE and my only solution is to make a new project for it to work again with the same exact codes. Any suggestions to ensure no such thing happen again in the future? Thank you in advance! Here are my codes in the controller:
[HttpPost]
public IActionResult CreateUser(Users usr)
{
if (!ModelState.IsValid)
{
ViewData["Message"] = "Invalid Input";
ViewData["MsgType"] = "warning";
return View("CreateUser");
}
else
{
string insert = #"INSERT INTO WBUsers(UserId, UserPw,FullName, Email, UserRole, Dob, ContactNo, usr.Billing_Address)
VALUES('{0}', HASHBYTES('SHA1', '{1}'), '{2}', '{3}', '{4}', '{5}', {6}, '{7}')";
if (DBUtl.ExecSQL(insert, usr.UserId, usr.UserPw, usr.FullName, usr.Email, usr.UserRole, usr.Dob, usr.ContactNo, usr.Billing_Address) == 1)
{
string template = #"Hi {0},<br/><br/>
Welcome to WorldBay!
Your userid is <b>{1}</b> and password is <b>{2}</b>. Please change your password upon login.
<br/><br/>Adminstrator";
string title = "Account Sign Up";
string message = String.Format(template, usr.FullName, usr.UserId, usr.UserPw);
string result = "";
bool outcome = false;
outcome = EmailUtl.SendEmail(usr.Email, title, message, out result);
if (outcome)
{
ViewData["Message"] = "Account has been created";
ViewData["MsgType"] = "success";
}
else
{
ViewData["Message"] = result;
ViewData["MsgType"] = "warning";
}
}
else
{
ViewData["Message"] = "Account cannot be created";
ViewData["MsgType"] = "danger";
}
return View("CreateUser");
}
}
DBUtil code consists of:
public static int ExecSQL(string sql, params object[] list)
{
List<String> escParams = new List<String>();
foreach (object o in list)
{
if (o == null)
escParams.Add("");
else
escParams.Add(EscQuote(o.ToString()));
}
DB_SQL = String.Format(sql, escParams.ToArray());
int rowsAffected = 0;
using (SqlConnection dbConn = new SqlConnection(DB_CONNECTION))
using (SqlCommand dbCmd = dbConn.CreateCommand())
{
try
{
dbConn.Open();
dbCmd.CommandText = DB_SQL;
rowsAffected = dbCmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
DB_Message = ex.Message;
rowsAffected = -1;
}
}
return rowsAffected;
}

did SubethaSmtp store emails somewhere?

I use the SubethaSmtp library as an email server and so far I have been able to run this server and test it by sending an email. Email information is printed in the output. As far as I know, smtp protocol is used to send emails. While IMAP protocol is used to receive emails. My question is, did SubethaSmtp store emails somewhere (such as a database or file)? In general, do I need a server other than SubethaSmtp server to receive emails? What will be the relationship between these two protocols?
My code is written in the following two Java classes:
BasicSMTPServer class:
package com.sojoodi;
import org.subethamail.smtp.server.SMTPServer;
public class BasicSMTPServer {
public static void main(String[] args) {
MyMessageHandlerFactory myFactory = new MyMessageHandlerFactory();
SMTPServer smtpServer = new SMTPServer(myFactory);
smtpServer.setPort(25000);
smtpServer.start();
System.out.println("smtpServer = " + smtpServer);
System.out.println("HostName = " + smtpServer.getHostName());
}
}
and MyMessageHandlerFactory class:
package com.sojoodi;
import org.subethamail.smtp.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MyMessageHandlerFactory implements MessageHandlerFactory {
public MessageHandler create(MessageContext ctx) {
return new Handler(ctx);
}
class Handler implements MessageHandler {
MessageContext ctx;
public Handler(MessageContext ctx) {
this.ctx = ctx;
}
public void from(String from) throws RejectException {
System.out.println("FROM:"+from);
}
public void recipient(String recipient) throws RejectException {
System.out.println("RECIPIENT:"+recipient);
}
public void data(InputStream data) throws IOException {
System.out.println("MAIL DATA");
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
System.out.println(this.convertStreamToString(data));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
}
public void done() {
System.out.println("Finished");
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
}
Maybe you can check the Receive emails with SubEtha SMTP and Spring Boot post and for you question about storing you can check the issues section in the related code repository as there is an issue same as yours.

Modify Existing alarms AWS

I want to know how do i read and modify all the alarms ? I am currently facing problem to read the next set of alarms. The first set contains first 50.
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
System.out.println(alarmsResult.getMetricAlarms().size());
System.out.println(alarmsResult.getNextToken());
DescribeAlarmsRequest describeAlarmsRequest1 = new DescribeAlarmsRequest();
describeAlarmsRequest1.setNextToken(alarmsResult.getNextToken());
DescribeAlarmsResult alarmsResult1 = cloudWatch.describeAlarms(describeAlarmsRequest1);
System.out.println(alarmsResult1.getMetricAlarms().size());
I did it the following way and it worked.
public class Alarms {
private static AmazonCloudWatchClient cloudWatch;
private static AmazonSNSClient client;
private static ClientConfiguration clientConfiguration;
private static final String AWS_KEY = "";
private static final String AWS_SECRET_KEY = "";
static {
BasicAWSCredentials credentials = new BasicAWSCredentials(AWS_KEY,AWS_SECRET_KEY);
cloudWatch = new AmazonCloudWatchClient(credentials);
clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeout(10000);
clientConfiguration.setSocketTimeout(30000);
clientConfiguration.setMaxErrorRetry(5);
client = new AmazonSNSClient(credentials, clientConfiguration);
}
public static void main(String args[]) {
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
//describeAlarmsRequest.setStateValue(StateValue.OK);
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
List<MetricAlarm> metricAlarmList = new ArrayList<>();
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
do {
describeAlarmsRequest.withNextToken(alarmsResult.getNextToken());
alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
} while (alarmsResult.getNextToken() != null);
int i = metricAlarmList.size();
System.out.println("size " + i);
for(MetricAlarm alarm : metricAlarmList){
System.out.println(i--);
modifyalarm(alarm);
}
}
private static void modifyalarm(MetricAlarm alarm) {
Dimension instanceDimension = new Dimension();
instanceDimension.setName("InstanceId");
instanceDimension.setValue(alarm.getAlarmName());
PutMetricAlarmRequest request = new PutMetricAlarmRequest()
.withActionsEnabled(true).withAlarmName(alarm.getAlarmName())
.withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
.withDimensions(Arrays.asList(instanceDimension))
.withAlarmActions(getTopicARN())
.withEvaluationPeriods(5)
.withPeriod(60)
.withThreshold(5.0D)
.withStatistic(Statistic.Average)
.withMetricName("StatusCheckFailed")
.withNamespace("AWS/EC2");
cloudWatch.putMetricAlarm(request);
}
private static String getTopicARN() {
ListTopicsResult listTopicsResult = client.listTopics();
String nextToken = listTopicsResult.getNextToken();
List<Topic> topics = listTopicsResult.getTopics();
String topicARN = "";
while (nextToken != null) {
listTopicsResult = client.listTopics(nextToken);
nextToken = listTopicsResult.getNextToken();
topics.addAll(listTopicsResult.getTopics());
}
for (Topic topic : topics) {
if (topic.getTopicArn().contains("status-alarms")) {
topicARN = topic.getTopicArn();
break;
}
}
return topicARN;
}
}

JTable unable to change cell value

I have created a method to created JTable as per below:
public void refTable(String jobNo) {
Report rp = new Report();
final String noJob = jobNo;
Map<Integer, String> jMap = rp.getReportInfo(jobNo);
Map<Integer, String> sortedMap = new TreeMap<Integer, String>(jMap);
String[] row = new String[sortedMap.size()];
Integer[] no = new Integer[sortedMap.size()];
String[] stat = new String[sortedMap.size()];
Boolean[] dev = new Boolean[sortedMap.size()];
String[] remark = new String[sortedMap.size()];
Boolean[] rem = new Boolean[sortedMap.size()];
userRemark = new String[sortedMap.size()];
tabSize = sortedMap.size();
int i = 0;
for (Integer key : sortedMap.keySet()) {
no[i] = key;
String[] val = sortedMap.get(key).split("###");
if (val[0].trim().equals("DEV")) {
stat[i] = "FAIL";
} else {
stat[i] = val[0].trim();
}
row[i] = val[1].trim();
dev[i] = false;
remark[i] = "";
//remark[i] = false;
//if(userRemark1[i]!=null)
userRemark[i] = RemarkDropDownList.userOthersReamrk;
//else
//userRemark[i] ="";
rem[i] = false;
i++;
}
DefaultTableModel model = new DefaultTableModel();
model.fireTableDataChanged();
jTable1.setModel(model);
model.addColumn("No:", no);
model.addColumn("Status:", stat);
model.addColumn("Details:", row);
model.addColumn("Non-Deviation", dev);
model.addColumn("Remarks", remark);
model.addColumn("Remove", rem);
model.addColumn("UR", userRemark);
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(30);
TableColumn col2 = jTable1.getColumnModel().getColumn(1);
col2.setPreferredWidth(30);
TableColumn col3 = jTable1.getColumnModel().getColumn(2);
TextRenderer renderer = new TextRenderer();
col3.setCellRenderer(renderer);
col3.setPreferredWidth(350);
CellRenderer cellRender = new CellRenderer();
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(cellRender);
col4.setPreferredWidth(50);
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
TableColumn col6 = jTable1.getColumnModel().getColumn(5);
col6.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col6.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col6.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
}
In my JTable I've created a button in column 5 like this.
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
The button basically create a new JFrame with combobox inside it like this.
public class RemarkDropDownList extends javax.swing.JFrame {
public static String userOthersReamrk = "test";
private String userSelectedItem = "File Issue";
String jobno;
int rowNo;
public RemarkDropDownList() {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
public RemarkDropDownList(String jobNo, int row) {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
this.jobno = jobNo;
this.rowNo = row;
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JComboBox cb = (JComboBox)evt.getSource();
userSelectedItem = (String)cb.getSelectedItem();
if(userSelectedItem.equalsIgnoreCase("others"))
{
this.lblOthers.setVisible(true);
this.txtOthers.setVisible(true);
}
else
{
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(userSelectedItem.equalsIgnoreCase("others"))
{
userOthersReamrk = txtOthers.getText().toString();
if(userOthersReamrk == null || userOthersReamrk.equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(null, "Please enter Remark");
}
}
else
{
userOthersReamrk = userSelectedItem;
//String [] remark = new String [1000];
///remark[rowNo] = userOthersReamrk;
ReportPanelMin rpm = new ReportPanelMin();
//rpm.userRemark1[rowNo] = remark[rowNo];
rpm.refTable(jobno);
this.setVisible(false);
}
}
}
Everything is working, but the last part. I've created a static global variable (userOthersReamrk) in RemarkDropDownList class (the new class) to hold user drop down selected value. I call the refTable function again to reload the table so i can assign the userOthersReamrk value to column no 7 like this userRemark = new String[sortedMap.size()];. When i debug, I can see the user selected value is assigned touserRemark array but its not population in the table. The column showing the default value test which i decalred in RemarkDropDownList. I know the code is so long, but i post everything to give better understanding on what im doing. What/where i need to make change so my user's selected value is shown in column 7 instead the default value.

HTTP Get to Report Server 2008 works with DefaultCredentials, fails with some NetworkCredentials

The following WithDefaultCredentials() works but WithCredentialsMe() fails with a http 401 returned ?
The difference is that
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
works OK against the report server 2008 url , but
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
comes back with a HTTP 401.
The console app is being developed by me so, there should not be a difference between DefaultCredentials and NetworkCredential. There is no problem with my Username and password.
Any ideas ?
static void Main(string[] args)
{
WithDefaultCredentials();
WithCredentialsMe();
}
public static void WithDefaultCredentials()
{
try
{
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_WithDefaultCredentitials.pdf", bytes.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void WithCredentialsMe()
{
try
{
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_Credentials_me_1.pdf", bytes.ToArray());
}
catch( Exception ex )
{
Console.WriteLine( ex.Message);
}
}
public static List<Byte> GetByteListFromUrl(string url, System.Net.ICredentials credentials)
{
List<Byte> lstByte = new List<byte>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (credentials != null)
{
request.Credentials = credentials;
}
var response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
int totalBytesRead = 0;
int bufferbytesRead = 0;
try
{
byte[] buffer = new byte[1024];
while ((bufferbytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bufferbytesRead;
if (bufferbytesRead < buffer.Length)
{
bufferbytesRead = bufferbytesRead - 1 + 1;
}
for (int i = 0; i < bufferbytesRead; i++)
{
var bToAdd = buffer[i];
lstByte.Add(bToAdd);
}
}
}
catch (Exception ex)
{
}
finally{}
//-Return
return lstByte;
}
With the help of http://forums.asp.net/t/1217642.aspx this code got me what I wanted ...
Next step is clean it all up and unit test in dev ...
public static void ReportServerWebService()
{
// wsdl /out:rs.cs /namespace:ReportService2005 http://mybox/ReportServer_SQLSERVER2008/ReportService2005.asmx?wsdl
/// wsdl /out:rsExec.cs /namespace:ReportExecution2005 http://mybox/ReportServer_SQLSERVER2008/ReportExecution2005.asmx?wsdl
ICredentials credentials = new NetworkCredential("myUserName", "myPassword", "hcml");
Guid invoiceID = new Guid("115ABBA9-61BB-4070-BD28-F572115A2860");
var rs = new ReportService2005.ReportingService2005();
var rsExec = new ReportExecution2005.ReportExecutionService();
rs.Credentials = credentials;
rsExec.Credentials = credentials;
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] bytPDF;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = "/ElfInvoice/ElfInvoice" ;
string _historyID = null;
bool _forRendering = false;
ReportService2005.ParameterValue[] _values = null;
ReportService2005.DataSourceCredentials[] _credentials = null;
ReportService2005.ReportParameter[] _parameters = null;
try
{
// Get if any parameters needed.
_parameters = rs.GetReportParameters( _reportName, _historyID, _forRendering, _values, _credentials);
// Load the selected report.
var ei = rsExec.LoadReport(_reportName, historyID);
// Prepare report parameter.
// Set the parameters for the report needed.
var parameters = new ReportExecution2005.ParameterValue[1];
// // Place to include the parameter.
if (_parameters.Length > 0)
{
parameters[0] = new ReportExecution2005.ParameterValue();
parameters[0].Label = "InvoiceID";
parameters[0].Name = "InvoiceID";
parameters[0].Value = invoiceID.ToString();
}
rsExec.SetExecutionParameters(parameters, "en-us");
bytPDF = rsExec.Render( format , deviceInfo , out extension , out encoding , out mimeType , out warnings , out streamIDs ) ;
try
{
File.WriteAllBytes(#"c:\temp\A_WithMyCredentitials_ReportServerWebService.pdf", bytPDF.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}