Thursday, April 30, 2015

else if statement allows false

Hello

I have the following code where i,m trying to see if a CustId exist or not and if it does return data from the database to the textboxes but if not it returns a message in the lblMessage.

But what is happing in my else if statement is allows false so it throws the lblMessage "can not find Customer Id" or an Exception is i change the code to

else if (CustID ==0){
//then code
}

 protected void Button1_Click(object sender, EventArgs e)
        {
            
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection1"].ConnectionString);
            int CustID = 0;
            SqlCommand command = new SqlCommand();

            command.Connection = conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "GetCustmer";
            command.Connection.Open();

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@ID";
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            param.Value = txtCustID.Text;
            command.Parameters.Add(param);
            int ID = table.Rows.Count;
            if (string.IsNullOrWhiteSpace(txtCustID.Text))
            {
                //throw new Exception("Id not provided.");
                lblMessage.Text = "You did not enter a Customer Number";

            }
            else if(CustID !=0)
            {
                adapter.SelectCommand = command;
                adapter.Fill(table);

                //txtCustID.Text = table.Rows[0].Field<string>("CustID");
                txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
                txtFirstname.DataBind();
                txtSurname.Text = table.Rows[0].Field<string>("Surname");
                txtSurname.DataBind();
            }
            else {
                lblMessage.Text = "Could not find customer number";
            }
            
        }

Thanks for your help

else if statement allows false

Hi,

custID will always be 0, just as being initialized, you never set it to an other value.

Like:

Int32.TryParse(txtCustID.Text, out CustID);
 

Regards,

  Thorsten


System.NullReferenceException was unhandled ?

here
dr = cmd.ExecuteReader();

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

So I have to build dynamic T-SQL because of a date parameter that will be provided. The Date Parameter will be provided in SSRS in normal MM/DD/CCYY format. So how do I then convert that date to my Oracle format NUMERIC(8,0) CCYYMMDD?

I tried this...

SET           @SQLQuery       =       @SQLQuery       +   'AND    MEMBER_SPAN.YMDEFF                                              <=                   '''''   +   CAST(@AsOfDate  AS      VARCHAR)        +   '''''   '       +   @NewLineChar;
SET             @SQLQuery       =       @SQLQuery       +   'AND    MEMBER_SPAN.YMDEFF                                              >=                   '''''   +   CAST(@AsOfDate  AS      VARCHAR)        +   '''''   '       +   @NewLineChar;

but that put it in the format of...

AND

MEMBER_SPAN.YMDEFF<=''2015-04-01''

AND

MEMBER_SPAN.YMDEFF>=''2015-04-01''

which is close...I think I just need to lose the "-"

Thanks for your review and am hopeful for a reply.

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Please check this?

SELECT replace(convert(VARCHAR, getdate(), 111) , '/', '-') 


Please click "Mark as Answer" if the post solves your problem - Thanks

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Try ISO style 112 with CONVERT:


--T-SQL
select CONVERT(Char(10),Cast('2015-04-01' as date),112) , CONVERT(Char(10),current_timestamp,112)

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Hi ITBobbyp,

For SQL Server 2012 and above, you can use FORMAT.

SELECT FORMAT(CAST('04/01/2015' AS DATE),'yyyyMMdd') AS DT

/*
DT
20150401
*/

If you have any question, feel free to let me know.

Eric Zhang
TechNet Community Support


How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

My Mistake. I have put a "-". Please try below

SELECT replace(convert(VARCHAR, getdate(), 111) , '/', '') 


Please click "Mark as Answer" if the post solves your problem - Thanks

AjaxControlToolkit CalendarExtender not working after publish

I am using the AjaxControlToolkit CalendarExtender in my web site and its working in the visual studio 2012 but after publish to IIS Calendar Extender control won't show !

asp.net code :

<asp:TextBox ID="txtFrom" runat="server" Width="200"></asp:TextBox>
<asp:Image ID="image1" runat="server" ImageUrl="~/Image/calendar.png" />
<ajaxToolkit:CalendarExtender ID="Calendar1" runat="server" TargetControlID="txtFrom" Format="dd.MM.yyyy" Enabled="true" PopupButtonID="image1" CssClass="cal_Theme1"></ajaxToolkit:CalendarExtender>

Web.config :

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://ift.tt/1eigFsq -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-RechnungProgramm-20140827102620.mdf;Initial Catalog=aspnet-RechnungProgramm-20140827102620;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="RechnungConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Rechnung.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /></controls>
    </pages>
    <membership>
      <providers>
        <!--
          ASP.NET Membership is disabled in this template. Please visit the following link http://ift.tt/1xKWZUh to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <!--
          ASP.NET Membership Profile is disabled in this template. Please visit the following link http://ift.tt/1xKWZUh to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </profile>
    <roleManager>
      <!--
            ASP.NET Membership Role is disabled in this template. Please visit the following link http://ift.tt/1xKWZUh to learn about the ASP.NET Membership support in this template
        -->
      <providers>
        <clear />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
    <handlers>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.1.0.4" newVersion="2.1.0.4" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="HtmlAgilityPack" publicKeyToken="bd319b19eaf3b43a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.4.9.0" newVersion="1.4.9.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

and master page ScriptManager :

 <form runat="server">
            <ajaxToolkit:ToolkitScriptManager runat="Server" EnableScriptGlobalization="true"
                    EnableScriptLocalization="true" ID="ScriptManager1" ScriptMode="Debug" CombineScripts="false" >
            <Scripts>
                <%--To learn more about bundling scripts in ScriptManager see http://ift.tt/1eMOMJk --%>
                <%--Framework Scripts--%>
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="bootstrap" />
                <asp:ScriptReference Name="respond" />
                <asp:ScriptReference Name="WebForms.js" Path="~/Scripts/WebForms/WebForms.js" />
                <asp:ScriptReference Name="WebUIValidation.js" Path="~/Scripts/WebForms/WebUIValidation.js" />
                <asp:ScriptReference Name="MenuStandards.js" Path="~/Scripts/WebForms/MenuStandards.js" />
                <asp:ScriptReference Name="GridView.js" Path="~/Scripts/WebForms/GridView.js" />
                <asp:ScriptReference Name="DetailsView.js" Path="~/Scripts/WebForms/DetailsView.js" />
                <asp:ScriptReference Name="TreeView.js" Path="~/Scripts/WebForms/TreeView.js" />
                <asp:ScriptReference Name="WebParts.js" Path="~/Scripts/WebForms/WebParts.js" />
                <asp:ScriptReference Name="Focus.js" Path="~/Scripts/WebForms/Focus.js" />
                <asp:ScriptReference Name="WebFormsBundle" />
                <%--Site Scripts--%>
            </Scripts>
            </ajaxToolkit:ToolkitScriptManager>

i am using AjaxControlToolkit.dll Version 4.5.7.1213

How can i fix this ?

AjaxControlToolkit CalendarExtender not working after publish

Hi Mazi.ar,

Please post your question to the below asp.net forum, for a better assistance on your issue, this forum is for C# code in specific:

http://forums.asp.net/

Regards,


Fouad Roumieh

System.NullReferenceException was unhandled ?

Here's my code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Store_Goods_List
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\miki\documents\visual studio 2012\Projects\Store Goods List\Store Goods List\Database1.mdf;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            cmd.Connection = cn;
            loadlist();
        }

        private void label3_Click(object sender, EventArgs e)
        {
            if (txtnum.Text != "" & txtname.Text != "" & txtstock.Text != "" & txtprice.Text!="")
            {
                cn.Open();
                cmd.CommandText = "Insert Info (product id,name,stock,price) values ('"+txtnum.Text+"','"+txtname.Text+"','"+txtstock.Text+"','"+txtprice.Text+"')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record inserted!","Programming");
                cn.Close();
                txtnum.Text = "";
                txtname.Text = "";
                txtstock.Text = "";
                txtprice.Text = "";
                loadlist();
            }
        }
        private void loadlist()
        {
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();
            listBox4.Items.Clear();
            cn.Open();
            cmd.CommandText = "select ' from info";
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    listBox1.Items.Add(dr[0].ToString());
                    listBox2.Items.Add(dr[1].ToString());
                    listBox3.Items.Add(dr[2].ToString());
                    listBox4.Items.Add(dr[3].ToString());
                }
            }
            cn.Close();
        }

        private void listBox4_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox l = sender as ListBox;
            if(l.SelectedIndex!= -1)
            {
                listBox1.SelectedIndex = l.SelectedIndex;
                listBox2.SelectedIndex = l.SelectedIndex;
                listBox3.SelectedIndex = l.SelectedIndex;
                listBox4.SelectedIndex = l.SelectedIndex;
            }
        }
    }
}

System.NullReferenceException was unhandled ?

Which line of your code gives you that error? Can you put a breakpoint to step in through?

chanmm


chanmm

System.NullReferenceException was unhandled ?

around here

            cmd.CommandText = "select ' from info";
            dr = cmd.ExecuteReader();
            if (dr.HasRows)

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

So I have to build dynamic T-SQL because of a date parameter that will be provided. The Date Parameter will be provided in SSRS in normal MM/DD/CCYY format. So how do I then convert that date to my Oracle format NUMERIC(8,0) CCYYMMDD?

I tried this...

SET           @SQLQuery       =       @SQLQuery       +   'AND    MEMBER_SPAN.YMDEFF                                              <=                   '''''   +   CAST(@AsOfDate  AS      VARCHAR)        +   '''''   '       +   @NewLineChar;
SET             @SQLQuery       =       @SQLQuery       +   'AND    MEMBER_SPAN.YMDEFF                                              >=                   '''''   +   CAST(@AsOfDate  AS      VARCHAR)        +   '''''   '       +   @NewLineChar;

but that put it in the format of...

AND

MEMBER_SPAN.YMDEFF<=''2015-04-01''

AND

MEMBER_SPAN.YMDEFF>=''2015-04-01''

which is close...I think I just need to lose the "-"

Thanks for your review and am hopeful for a reply.

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Please check this?

SELECT replace(convert(VARCHAR, getdate(), 111) , '/', '-') 


Please click "Mark as Answer" if the post solves your problem - Thanks

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Try ISO style 112 with CONVERT:


--T-SQL
select CONVERT(Char(10),Cast('2015-04-01' as date),112) , CONVERT(Char(10),current_timestamp,112)

How do I convert a SQL Server Date MM/DD/CCYY to an Oracle Date formatted as NUMBER(8,0)

Hi ITBobbyp,

For SQL Server 2012 and above, you can use FORMAT.

SELECT FORMAT(CAST('04/01/2015' AS DATE),'yyyyMMdd') AS DT

/*
DT
20150401
*/

If you have any question, feel free to let me know.

Eric Zhang
TechNet Community Support


index help

hello,
In my table I have columns like

Year int  not null
week int  not null
type int  not null
code nchar(5) not null
exchange  nvarchar(3)  null

c1    nvarchar(10) null
c2    nvarchar(10) null
c3    nvarchar(10) null
.
.
.
.

c20   nvarchar(10) null

In table I will have Uniqueness of Year,Week,Type,Code,Exchange,c1,c2..,c20
 
In my most of the query I have condition like

where
             Year=@year and period =@period and type=@type and code=@code and exchange=@exchange and c1=@c1 and c2=@c2 and c3=@c3.... and c4=@c20

In this scenario should I make single index with include columns like below

CREATE NONCLUSTERED INDEX IX_table
ON table ( Year,period,type,code,exchange)
INCLUDE (c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20)

Or I will create 20 indexes like below

CREATE NONCLUSTERED INDEX IX_table
ON table ( Year,period,type,code,exchange,c1)

CREATE NONCLUSTERED INDEX IX_table
ON table ( Year,period,type,code,exchange,c2)


and so on

MediaCapture: can we specific size limitation?

With Windows.Media.Capture.MediaCapture, can we specify a size limit so that this event(RecordLimitationExceededEventHandler) is fired and recording is stopped?

If not, what is the proper way to monitor file size while recording?

Thanks!


Te-Cheng Hsieh

Creating a trial app with a feature that expires after being used twice

I want to add a feature to my app that user can avail only twice or thrice in the trial mode. I am unable to figure out which purchase mode should I implement.

I successfully implemented the in-app-purchase for making the feature available for lifetime. But how should I go about limiting its usage if the user has not bought it?

According to the sample code I am following I have these options:

Expiring Product: This allows me to expire the feature after certain period of time but I need to expire the product after number of usage.

InAppPurchase: I can purchase feature through this but I cannot limit the feature in trial mode.

ConsumableInAppPurchase: Again it requires the user to buy the feature first and then it can be consumed.

I figured that if I can save an int in local settings of app the first time app is used and then decrement it until its 0, and then prompt the user to buy, it will do the job. But if I use this method user can always delete the settings file and my app wouldn't know that it is not being used the first time. 

Can anybody tell me how I can achieve my requirement?

Thanks


Creating a trial app with a feature that expires after being used twice

You cannot achieve this with the built-in trial mode.  It is based entirely on the time limit you choose when publishing the app.  After the time limit is up, the app will stop functioning.

To do what you want to do, you will have to write your own code.  One of my apps, a word processor for example, lets the user use the app with full features for 7 days.  After 7 days, instead of stop opening, it simply goes into read-only mode until the user buys it.  The advantage of doing it this way instead of making the app non-functioning forever after 7 days is the user will always have the opportunity to see what's new in my future updates.  I don't want to lose potential customers!  Nothing the user can do to reset the 7 days trial. They can uninstall and reinstall as many times as they want.  They can delete the settings file all they want.  My method doesn't require the app to check over the internet.  I'm sure if you think hard enough you will figure out a way like I did.  I'm just letting you know that there is a way and it is possible.  I just don't want this method to be known too widely.

Creating a trial app with a feature that expires after being used twice

You cannot achieve this with the built-in trial mode.  It is based entirely on the time limit you choose when publishing the app.  After the time limit is up, the app will stop functioning.

To do what you want to do, you will have to write your own code.  One of my apps, a word processor for example, lets the user use the app with full features for 7 days.  After 7 days, instead of stop opening, it simply goes into read-only mode until the user buys it.  The advantage of doing it this way instead of making the app non-functioning forever after 7 days is the user will always have the opportunity to see what's new in my future updates.  I don't want to lose potential customers!  Nothing the user can do to reset the 7 days trial. They can uninstall and reinstall as many times as they want.  They can delete the settings file all they want.  My method doesn't require the app to check over the internet.  I'm sure if you think hard enough you will figure out a way like I did.  I'm just letting you know that there is a way and it is possible.  I just don't want this method to be known too widely.

Are you saying your method is different from the 'Expiring Product' option I mentioned? To me it sounds the same as that

Creating a trial app with a feature that expires after being used twice

What I'm saying is the built in trial mode for windows 8 app makes the app completely non-functional once the trial expires.  In order to achieve what you want, which is full functionality either for a time or for a number of app opening before going into limited mode, you will have to write your own code for it. 

I'm just telling you that it is possible to achieve this.  Took me a time but eventually I figured out how.  I'm assuming you do not want your app to keep track of the specific user and cross check with a record stored online somewhere.  This would be another option. 

The point is there's a way because I've effectively achieved this.  I don't want to just say it out loud because I don't want my method to be widely known.  Just keep thinking about it and you'll figure out how to do this.

Creating a trial app with a feature that expires after being used twice

What I'm saying is the built in trial mode for windows 8 app makes the app completely non-functional once the trial expires.  In order to achieve what you want, which is full functionality either for a time or for a number of app opening before going into limited mode, you will have to write your own code for it. 

I'm just telling you that it is possible to achieve this.  Took me a time but eventually I figured out how.  I'm assuming you do not want your app to keep track of the specific user and cross check with a record stored online somewhere.  This would be another option. 

The point is there's a way because I've effectively achieved this.  I don't want to just say it out loud because I don't want my method to be widely known.  Just keep thinking about it and you'll figure out how to do this.

Yeah I think I know what code you are referring to! Thanks though :)

Is there any possibility to block emails of subscriptions we are about to create in 2008 (folder level) and enable back the emails once we are done creating the subscriptions

Hi,

We are migrating our Reporting Server from 2005 to 2008 and we have around 3500 timed subscriptions which are scheduled daily/weekly/monthly.

It takes around 1 week to recreate all these subscriptions in 2008 reporting server as we are using C# Code (to get the new subscriptionID from 2008 for further use). In this 1 week the subscription emails will be duplicated as they are sent from both 2005 and 2008 (created) to end user but we can't disable the SMTP for the 2008 report server as there are other projects (separated at folder level) working on it.

The Question here is, "Is there any possibility to block emails of subscriptions we are about to create in 2008 (only to our folder) and enable back the emails once we are done migrating to 2008?".

Regards,

Prabhat Y.


Is there any possibility to block emails of subscriptions we are about to create in 2008 (folder level) and enable back the emails once we are done creating the subscriptions

Hi Prabhat Y,

Per my understanding that you are doing the migration from SSRS 2005 to SSRS 2008 and now you are re-creating the 3500 subscriptions in the SSRS 2008, so you want to the new created subscription in SSRS 2008 will be pause and not execute at this time, right?

Generally, we have several method to pause the subscription processing, please reference to details information below:

  1. When you created an subscription, an new Sql Server Agent job will be created too, so you can you can just uncheck the 'enabled' checkbox in the job properties as below to disable the execution of the job,you can also  stop the SQL Server Agent Services manually, all your subscriptions will stop running:

    More information, Please reference to: 
    How to temporarily stop SSRS subscriptions
  2. You can also disable a Shared Data Source, pause a Shared Schedule to pause the subscription processing.
    Pause Report and Subscription Processing

If you still have any problem, please feel free to ask.

Regards,
Vicky Liu


Vicky Liu
TechNet Community Support


SSRS

Hello,

I have table1 that is using  dataset-A. I grouped this table by date. I have other dataset- B which contains total_qty column.

I have to sum this column(total_qty) and show the result in table1 under  every group total  .

Data set A columns:

Date

company_code

location_name

volumes

Data set B columns: 

Date

Company_code

Total_Qty

How can I get Sum(total_qty) from Dataset B into table1 under group total ?Also,total_Qty should change as it is placed in group?

SSRS

Hi shilpa288,

Per my understanding that you have two tables and you create two datasets related to the two tables, now you want to sum the Total_Qty which comes from the table2 to display in the report based on table1 which grouped by the field "Date", right?

As you want to get the SUM(Total_Qty) grouped by the date, so I assumed the field date, Company_code  in the table1 are the same with that in the table2. If so we can use  the lookup function to get the field "Total_Qty" to display in the report and then use the expression " SUM(Total_Qty,"Date")" to get the total sum.

Details information below for your reference:

  1. Before use the lookup() function, make sure your SSRS version is 2008 R2 or later, or it will not support this function.
  2. Make sure you have an relationship field which is unique to be involved in this function, for example: Company_code, then you can add expression like below:
    Expression1:
    =Lookup(Fields!CompanyCode.Value,Fields!CompanyCode.Value,Fields!TotalQty.Value, "DataSetB")
  3. Right click the row group "Date" to Add total after, use below expression to sum the total:
    Expression2:
    =SUM(Lookup(Fields!CompanyCode.Value,Fields!CompanyCode.Value,Fields!TotalQty.Value, "DataSetB"),"Date")
  4. Preview like below:

More details information about the Lookup() and LoopupSet() function:
Lookup Function (Report Builder and SSRS)
LookupSet Function (Report Builder and SSRS)

If your data is not suitable to use the Lookup() or LookupSet() function, I will suggest you to modify the query to join the two tables to get the sum and not create two seperate datasets.

If you still have any problem, please try to provide sample data and more details information.

Regards,
Vicky Liu


Vicky Liu
TechNet Community Support


New document button adds calendar entry??

Hi BrinkyH,

In my test, the issue doesn't happen in SharePoint 2010, but does happen in SharePoint 2013. The build version for my SharePoint 2010 is 14.0.4762.1000. Please let me know your farm build version.

Besides, when I test the issue in SharePoint 2013, I noticed that the issue happens only when the calendar web part is below the document library web part, and if I change the order of them, the issue disappear. Please test this method in your environment.

Thanks,
Reken Liu


TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.

New document button adds calendar entry??

Hi Reken Liu,

I'm using SharePoint 2010 build 14.0.7137.5000. I've also tested the issue on another farm (also SP2010) from another SharePoint vendor and they have the same issue.

Also changing the order in which the web parts are placed, does not seem to matter. What I did notice is if I add another document library to the page, the new document button works fine. However the drop down menu for new document now actually says Event.

Hope this helps.

Regards,

BrinkyH

New document button adds calendar entry??

Hi BrinkyH,

I have to say the issue is a known issue in some version of SharePoint, and the same issue also happened in SharePoint Online, which has been fixed by a back end hot fix.

To fix the issue in your environment, please try upgrading your SharePoint to the latest CU, or you can remove the existing document library web part, and re-add it. Here's a link about SharePoint 2010 build numbers for your reference:

http://ift.tt/1IuqEYP

Thanks,
Reken Liu  


TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.

JSOM numeric paging, Go to a specific page

I am creating a paged list in SharePoint 2010 using JSOM withe help of following link

http://ift.tt/1p0waGy

I have implemented next or back paging but I could not find any way to do "numeric" paging, for example If I am on page 1,  I can't go directly to page 3.

Is it possible?


JSOM numeric paging, Go to a specific page

Hi,

Per my understanding, you might want to create a custom list with “numeric” paging functionality by following the demo you provided.

As the retrieved result set is controlled by the two parameters: pageIndex and pageSize, a thought is that you can add your custom logic to control the values of the two parameters to implement the “numeric” paging.

Feel free to reply if there is any progress.

Thanks 

Patrick Liang


TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.

Linking and Restricting Custom Forms

I've inherited part of a SharePoint site that my company uses for a class it offers. In the past new students were to fill out a Word doc with their information and send it in to have the instructors manually input the data. I'm trying to create a new public form for the data students input and have it fill in the appropriate fields in the instructor form. The 2 will be virtually the same except the Instructor version will have more fields (i.e class number, grades, etc) and will only be able to be accessed by specific people. Please help!

FYI

I have little SharePoint coding experience and do not have "FULL" access to the system only rights to change these specific pages.

Linking and Restricting Custom Forms

Hi,

As I understand, your requirement is that the Instructor version have more fields (i.e class number, grades, etc) and these fields cannot be seen by students.

Do you want to use the two forms or only one form to achieve it?

I recommend you to use one form to achieve it. If using one form, you could hidden these fields in the form when the users are students.

You could select the controls you want to hide, and add the format rule on these controls, and set the rules for these controls. You could store the all users in another list, when you add the rules, you should search the user in that list, then to tell if the user is student or instructor.

The article below is about Hiding Fields in InfoPath 2010 - Conditional Formatting. You could refer to the article for details.

http://ift.tt/1bIEwSb

Best regards,

Sara Fan


TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.


I want to learn 2D game programming. But, I am confused!

I want to make a 2D game in C#. I have begun learning C# on my own. But, I am confused sbout what to learn after c# to make a game. I hear many things like XNA, MDX, Monogame, SlimDX, SharpDX, Frameworks, game engines, IDE's etc. To me all of this has caused a great confusion. The C# game tutorial I am learning is based on MDX (Managed DirectX). Now, I realise that MDX and XNA is dead. I am confused if I want to change my tutorial itself. Can anyone clear things out for me and tell what i need to learn step by step? I really don't even know what all the sh*t (.NET ,XNA, Monogame, SharpDX, xxx, xxxx, xxxx etc.) really is or what it does or which is better or even what the differences are. So please explain everything to me. Please help!

I want to learn 2D game programming. But, I am confused!

hello , if you want to create games under c# i would recommend using unity 5 ;) it is free now. internet is full of tutorials. after that, you can start learning c++ and opengl or directx etc.

I want to learn 2D game programming. But, I am confused!

Hi,

You can refer to the Books:

Beginning .NET Game Programming

Beginning C# Game Programming

Few other useful links:

Coding 4 Fun is a great .NET resource that has quite a few user-created games. They also have a book and a 2-D game primer

Tutorial Listing at C# corner

C# Game Tutorial for Beginners (video)

Link to more game programming e-books

Advanced Topics

The Farseer Physics Engine on Codeplex would be a good next step once you get comfortable with programming games.


Please mark as answer or vote as helpful if my reply does

I want to learn 2D game programming. But, I am confused!

I really don't even know what all the sh*t (.NET, XNA, Monogame, SharpDX, MDX, xxx, xxxx, xxxx etc.) really is or what it does or which is better or even what the differences are. So please explain everything to me.

I want to learn 2D game programming. But, I am confused!

I really don't even know what all the sh*t (.NET, XNA, Monogame, SharpDX, MDX, xxx, xxxx, xxxx etc.) really is or what it does or which is better or even what the differences are. So please explain everything to me.

Case statement Help needed

I have a Table ManageGroups here`s the structure

P_ID Varchar(10) Not null, = 'Abc13'

Producttype varchar(20) not null, = 'PCPC'

LineofBusiness varchar(10) not null = 'Comm' and ' non comm'

I have a resultset which lists me all the products there are several products which are sold as 'Comm' and 'non Comm', I am trying to identify all the PID`s which are the following.

1.) Commercial

2.) Non Commercial

3.) Both in Commercial and NonCommercial 

My resultset should look like this

PID        LineoFBusiness
abc123        Commercial
bbc112        Non Commercial
Sam100      Commercial & Non commercial



Can you help me with this ?


FM

Case statement Help needed

Hi

Try this

select coalesce(com.p_Id,nc.P_Id),
       isnull(com.LineofBusiness,'') +
       case when com.LineofBusiness is not null and nc.LineofBusiness is not null then ' & ' else '' end +
       isnull(nc.LineofBusiness,'')   
From
(select P_Id, 'Commercial' as LineofBusiness
from pg_test.Test
where LineofBusiness = 'Comm'
Group by P_Id, LineofBusiness) com

Full outer join
(
select P_Id, 'Non Commercial' as LineofBusiness
from pg_test.Test
where LineofBusiness = 'Non Comm'
Group by P_Id, LineofBusiness
) nc
on nc.P_Id = com.P_Id

Case statement Help needed

Here is one way

SELECT
        P_ID,
        CASE
                WHEN COUNT(DISTINCT LineOfBusiness) = 1 AND MAX(LineOfBusiness) = 'Commercial' THEN 'Commercial'
                WHEN COUNT(DISTINCT LineOfBusiness) = 1 AND MAX(LineOfBusiness) = 'Non Commercial' THEN 'Non Commercial'
                ELSE 'Commercial & Non Commerical'
        END AS LineOfBusiness
FROM
        YourTable
GROUP BY
        P_ID;

If you don't expect the data to be used where the collations may be different, it perhaps could be simplified to something like shown below (but I would prefer my first query because it is unambiguous regardless of collation)

SELECT
        P_ID,
        CASE
                WHEN MAX(LineOfBusiness) = 'Commercial' THEN 'Commercial'
                WHEN Min(LineOfBusiness) = 'Non Commercial' THEN 'Non Commercial'
                ELSE 'Commercial & Non Commerical'
        END AS LineOfBusiness
FROM
        YourTable
GROUP BY
        P_ID;

Case statement Help needed

Hello Farhan1,

Based on my understanding, to achieve your requirement you can follow the below sample.

USE TestDB
GO

CREATE TABLE ManageGroups(
P_ID Varchar(10) Not null DEFAULT('Abc13'),

Producttype varchar(20) not null DEFAULT('PCPC'),

LineofBusiness varchar(10) not null CHECK(LineofBusiness IN ('Comm' , 'Non comm'))
)
--drop table ManageGroups

INSERT INTO ManageGroups(P_ID,LineofBusiness)
VALUES
('Abc13','Comm'),
('bbc112','Non comm'),
('sam100','Comm'),
('sam100','Non comm')

SELECT DISTINCT P_ID ,
REPLACE(STUFF((SELECT ','+LineofBusiness
 FROM ManageGroups T1
 WHERE T1.P_ID=T2.P_ID
 FOR XML PATH('')),1,1,''),',','&') LineofBusiness FROM ManageGroups T2

DROP TABLE ManageGroups

/*
P_ID    LineofBusiness
Abc13   Comm
bbc112  Non comm
sam100  Comm&Non comm
*/

If you have any question, feel free to let me know.

Eric Zhang
TechNet Community Support


Error "Incorrect syntax near the keyword 'Select'."

There's no need of values when you're using select as a source

this is enough

DECLARE @DATEPROCESS DATETIME;

SET @DATEPROCESS = CAST(DATEADD(DAY, -((DATEPART(WEEKDAY, GETDATE()) + 1 + @@DATEFIRST) % 7), GETDATE()) AS DATE)

insert into tempjoin([PART], [SPLRNAME], [SHIPDAYS], [SPRICE]) 
Select distinct
RC. CAT_PART AS PART, 
RC. CAT_SUPPLIER AS SUPPLIER, 
FFC.[Ships Within Days] AS SHIPDAYS,
ffc.[Sell Price] AS SPRICE
from fri_full_Catalog FFC
INNER JOIN R5PARTS RP 
ON (RP.PAR_UDFCHAR06 = FFC.[DSSI ITEM #] 
AND RP.PAR_ORG='USA' AND FFC.fri_Org='USA' 
and FRI_CREATED=@DATEPROCESS)
INNER JOIN R5CATALOGUE RC 
ON RP.PAR_CODE=RC.CAT_PART 
AND RC.CAT_PART_ORG='USA'
AND (RC.CAT_SUPPLIER=REPLACE(REPLACE([SPLR NAME],'&','-'), '''', '') 
and ((FFC.[Ships Within Days] <>  RC.CAT_LEADTIME)  OR (FFC.[Sell Price]<> RC.CAT_GROSS)))

Also using expressions in join condition can cause performance hit for large datasets as it wont be able to use an index even if one exists on the columns


Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
----------------------------
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page

Error "Incorrect syntax near the keyword 'Select'."

Try the below:

DECLARE @DATEPROCESS DATETIME;
SET @DATEPROCESS = CAST(DATEADD(D, -((DATEPART(WEEKDAY, GETDATE()) + 1 + @@DATEFIRST) % 7), GETDATE()) AS DATE)
insert into tempjoin([PART], [SPLRNAME], [SHIPDAYS], [SPRICE]) 
Select distinct
RC.CAT_PART AS PART, 
RC.CAT_SUPPLIER AS SUPPLIER, 
FFC.[Ships Within Days] AS SHIPDAYS,
ffc.[Sell Price] AS SPRICE
from fri_full_Catalog FFC
INNER JOIN
R5PARTS RP ON (RP.PAR_UDFCHAR06 = FFC.[DSSI ITEM #] AND RP.PAR_ORG='USA' AND FFC.fri_Org='USA' and 
FRI_CREATED=@DATEPROCESS)
INNER JOIN
R5CATALOGUE RC ON RP.PAR_CODE=RC.CAT_PART AND RC.CAT_PART_ORG='USA'
AND (RC.CAT_SUPPLIER=REPLACE(REPLACE([SPLR NAME],'&','-'), '''', '') and 
((FFC.[Ships Within Days] <>  RC.CAT_LEADTIME)  OR (FFC.[Sell Price]<> RC.CAT_GROSS)))


Please mark this reply as answer if it solved your issue or vote as helpful if it helped.
 [Blog]

Error "Incorrect syntax near the keyword 'Select'."

Thank you all. Issue has been fixed after following the steps provided by Visakh and Latheesh.

[WP8.1][C#]Why when I try to upload an Image with Windows Phone it uploads a random thing?

I'm trying to upload an image from my Windows Store App (Windows Phone 8.1) to hosting (using PHP) but always when I "uploaded" the image, and I check its result the "image" it's a corrupted file. I think it's related to the byte array conversion but I haven't found another way to do it. This is my code:

C# Code:

byte[] ConvertBitmapToByteArray()
        {
            WriteableBitmap bmp = bitmap;

            using (Stream stream = bmp.PixelBuffer.AsStream())
            {
                MemoryStream memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }

        public async Task<string> Upload()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    using (var content =
                        new MultipartFormDataContent())
                    {
                        byte[] data = ConvertBitmapToByteArray();
                        content.Add(new StreamContent(new MemoryStream(data)), "userfile", fileNewImage);

                        using (
                           var message =
                               await client.PostAsync("http://ift.tt/1KwegGL;, content))
                        {
                            var input = await message.Content.ReadAsStringAsync();

                            return input;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

PHP code:

<?php
        header('Content-Type: application/json');
        $uploaddir = getcwd();
        $uploadfile = $uploaddir . "/" . basename($_FILES['userfile']['name']);

        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                echo '{"result": "sucessfull"}';
        } else {
           echo '{"result": "-1"}';
        }?>

I wish someone could give me an idea about what I my mistake and how to fix it. Thanks in advance for your worthy knowledge.

Federico Navarrete


[WP8.1][C#]Why when I try to upload an Image with Windows Phone it uploads a random thing?

Hi FANMixco,

I did not test your code, but I think it's better to do some self-check by trying the sample: http://ift.tt/1KwegGJ

You should be able to know how to upload things to the server by the HttpClient, the code you convert image to byte array looks fine.

--James


We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

[WP8.1][C#]Why when I try to upload an Image with Windows Phone it uploads a random thing?

Hi Federico,

To help clarify your post and let people easily tell what it is about, please use a clear and concise subject and include applicable tags.

We will help to modify the tag base on this sticky post, and thanks for your understanding.

--James


We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

Is there any option to find out the User Own Mobile number Using c#?

Hi,

we are developing windows phone application. we need to show  user own mobile number in the app.

Could  you please tell me about the possible to get the User mobile number in windows phone 8 0r 8.1 using c# ?

Thanks in advance

Regards

Velmurugan D

Rendering Options for Report Specific

Hi,

I want to Set Rendering Extension Report based,

Example

Report 1 should have the rendering options of EXCEL and PDF.

Report 2 should have the rendering extension of EXCL only.

I referred below link for change the rendering extension.

http://ift.tt/1lSjNP3 

but its for all the reports format.


GVRSPK VENI

Rendering Options for Report Specific

Hi,

Where you want to render the report, I mean on report server or in subscription.

Report Server we cant set the report specific render format.

On Subscription:-

You can create the data driven subscription where you can specify the report format from database (select query of the format column from pre-defined database table).

Report 1 -- 2 subscription one for EXCEL, one for PDF

Report 2- 1 subscripton for excel

Thanks

Prasad

Rendering Options for Report Specific

Hello,

You can not defined the allowed export format per Report, only on server level: RSReportServer Configuration File => DefaultRenderingExtension

See also http://ift.tt/1FzmYUIdisabling-export-option-for-a-single-individual-ssrs-report


Olaf Helper

[ Blog] [ Xing] [ MVP]

Rendering Options for Report Specific

Hi Prasad,

Thanks for your reply.

could you explain the steps of Data Driven subscription Render format changes Report Specific.


GVRSPK VENI

Rendering Options for Report Specific

Hi Olaf Helper,

in that second Link , they just remove excel option specifically.

how to hide CSV, HTML, Tiff, XML, Word Except Excel and PDF.

Can you please give the code like below.

RemoveOption("/ReportSamples/10000rows", "Excel");


GVRSPK VENI

Rendering Options for Report Specific

Hi GVRSPK,

Per my understanding that you want to get different rendering format in the rendering options for different reports when you are creating the subscription.

I have tested on my local environment and we can achieve this by adding some jquery code in the SubscriptionProperties.aspx file which path like:C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\Pages

Details information below for your reference:

  1. Open the SubscriptionProperties.aspx file and add below code at the last:

<script src="http://ift.tt/KxYiSw; type="text/javascript"></script> <script type="text/javascript"> $(function() { var result = new RegExp('[\?&]ItemPath=([^&#]*)').exec(window.location.href)[1]; var reportName = result.split('%2f')[result.split('%2f').length - 1]; //alert(reportName); if (reportName == "Report1") { $("#RenderFormatID option[value='XML']").remove();//Remove XML render format }
if (reportName == "Report2") {
$("#RenderFormatID option[value='EXCEL']").remove();//Remove EXCEL render format
} }); </script>

You can find all the values in the option tag in the source code as below:

Once the code has been added, you can see the change immediately and if you want to roll back to default setting, just remove the code in the SubscriptionProperties.aspx file.

If you still have any problem, please feel free to ask.

Regards,
Vicky Liu


Vicky Liu
TechNet Community Support


Can I retrieve a result set from Oracle and then incorporate that result set into my main SQL Server Stored Procedure?

So I have a chunk of data that only resides in Oracle. So I need to capture that information from Oracle. Now before you get over zealous, I did try with an OPENQUERY and it took FOREVER! And I don't know why the OPENQUERY took FOREVER but if I run the same query directly against Oracle it runs very quickly...like 20 seconds.

So now I'm wondering...can I build a dataset in my SSRS Report that uses an Oracle Data source and an Oracle Stored Procedure in its Dataset that I'll create to aggregate this subset of data and then utilize its result set back in my main reporting Dataset that will utilize SQL Server? And how can I do that? Can I make my main Dataset reference, say, a #TemporaryTable that is created from my Oracle Dataset in its

I'll continue to Google a few things as I await your review and hopefully a reply.

Thanks in advance for your help.

Can I retrieve a result set from Oracle and then incorporate that result set into my main SQL Server Stored Procedure?

Hi ITBobbyP,

According to your description you want to use data from a Oracle data source into a DataSet which retrieving data from SQL Server. Right?

In Reporting Services, we can have multiple data sources in one project pointing to different database. And we can use separated dataset to retrieve data from different data source. However, it's not supported to combine the two datasets together directly. We can only use Lookup(), LookupSet() function to combine fields from different dataset into one tablix when there are common columns between two datasets. This is the only way to make tow result sets together in SSRS.

Reference:
Lookup Function (Report Builder and SSRS)
LookupSet Function (Report Builder and SSRS)

Best Regards, 


Simon Hou
TechNet Community Support


I want to learn 2D game programming. But, I am confused!

I want to make a 2D game in C#. I have begun learning C# on my own. But, I am confused sbout what to learn after c# to make a game. I hear many things like XNA, MDX, Monogame, SlimDX, SharpDX, Frameworks, game engines, IDE's etc. To me all of this has caused a great confusion. The C# game tutorial I am learning is based on MDX (Managed DirectX). Now, I realise that MDX and XNA is dead. I am confused if I want to change my tutorial itself. Can anyone clear things out for me and tell what i need to learn step by step? Please help!

I want to learn 2D game programming. But, I am confused!

hello , if you want to create games under c# i would recommend using unity 5 ;) it is free now. internet is full of tutorials. after that, you can start learning c++ and opengl or directx etc.

AppDomain is refusing to find dll dependencies

Hello again.

I had some health problems and less free time to work on this issue, which is why it took me this long for this :

I tried to apply suggestions from Mike Danes, however i still get the same result : FileNotFoundException.

When i use VS to check the operations step by step, i can see the program found the right dll and loaded it, however it seems it is unable to find it's dependencies.

Here is the Fusion Log i got that has weird paths :

=== Pre-bind state information ===
LOG: DisplayName = WAM.Modules.AlertScanner, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: E:\Projects\VS\Warframe Activity Manager\WAM.Desktop\bin\Debug\WAM.Desktop.exe.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/WAM.Modules.AlertScanner.DLL.
LOG: Attempting download of new URL file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/WAM.Modules.AlertScanner/WAM.Modules.AlertScanner.DLL.
LOG: Attempting download of new URL file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/WAM.Modules.AlertScanner.EXE.
LOG: Attempting download of new URL file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/WAM.Modules.AlertScanner/WAM.Modules.AlertScanner.EXE.

The first wrong thing is the he first attempt to download the assemblt file in file:///E:/Projects/VS/Warframe Activity Manager/WAM.Desktop/bin/Debug/WAM.Modules.AlertScanner.DLL. The path is the application path, not the path to the modules fodler which should be http://file/E:\Projects\VS\Warframe Activity Manager\Modules\Debug\AlertScanner. The same applies to the next attempts.

I have added a class file in the WAM.Common.Core.dll assembly :

using System;
using System.IO;
using System.Reflection;

namespace WAM.Common.Core
{
    public class PluginAssemblyLoader : MarshalByRefObject
    {
        public Assembly GetAssembly(String path)
        {
            try
            {
                return Assembly.LoadFile(Path.GetFileNameWithoutExtension(path));
            }
            catch (Exception)
            {
                return null;
                // throw new InvalidOperationException(ex);
            }
        }
    }
}

And the plugin manager code looks as this :

public Plugin(String path, Type moduleType)
        {
            if (String.IsNullOrEmpty(path))
                throw new ArgumentException("Plugin : path is null or empty");
            if (moduleType == null)
                throw new ArgumentException("Plugin : moduleType is null");

            _moduleType = moduleType;
            AppDomainSetup s = new AppDomainSetup();
            s.ApplicationName = Path.GetFileNameWithoutExtension(path);
            s.ApplicationBase = Path.GetDirectoryName(path);
            s.CachePath = Path.Combine(Path.GetDirectoryName(path), "cache" + Path.DirectorySeparatorChar);
            s.ShadowCopyFiles = "true";
            s.ShadowCopyDirectories = Path.Combine(Path.GetDirectoryName(path), "sc" + Path.DirectorySeparatorChar);
            _domain = AppDomain.CreateDomain(Path.GetFileNameWithoutExtension(path), null, s);

            Type type = typeof(PluginAssemblyLoader);
            PluginAssemblyLoader loader = (PluginAssemblyLoader)_domain.CreateInstanceAndUnwrap(
                type.Assembly.FullName,
                type.FullName);
            _assembly = loader.GetAssembly(path);
            
            var assemblies = _domain.GetAssemblies();
            foreach (var ass in assemblies)
            {
                try
                {
                    foreach (IList<Type> t in ass.GetTypes())
                    {
                        foreach (var tpe in t)
                            if (_moduleType.IsAssignableFrom(tpe))
                                _modules.Add(tpe);
                    }    
                }
                catch (Exception)
                {
                    break;
                }
            }
        }

Another thing that bothers me is that catch should catch the exceptions thrown by Assembly.LoadFile() and only return null, but i still get it once PluginAssemblyLoader.GetAssembly() returns. Is that normal?


AppDomain is refusing to find dll dependencies

Apparently you have just reinvented AppDomain.Load and its problem, loading the assembly in both domains. You have that loader which runs in the plugin appdomain and you call its GetAssembly method from the main appdomain. How will the main appdomain get its hands on that assembly? Well, it will try to load it as well.

 

AppDomain is refusing to find dll dependencies

The aim was to use the MarshalByRef to load the plugins into the secondary domains only.

Which means i did something wrong. As i said, i put the PluginAssemblyLoader in the Core assembly (referenced almost everywhere, meaning in the modules too). Plugin is a class that will contain the domain and the assemblies for the module, which is why i referenced it in my main app and why it has a reference to the PluginAssemblyLoader.

Did i misunderstand how this works?

AppDomain is refusing to find dll dependencies

"The aim was to use the MarshalByRef to load the plugins into the secondary domains only."

Yes but you ended up returning the Assembly object from the plugin appdomain to the main appdomain and that defeats the purpose of the loader. Whatever work (GetTypes, IsAssignableFrom etc.) you need to do with the plugin assembly needs to happen in the plugin domain.

The main domain should only see plugin interfaces from the core assembly, it should never get Assembly or Type objects from the plugin appdomain.

Wednesday, April 29, 2015

How to perform rotation along with scaling for a text in GDI+

Hi,

I'm not sure, if I understand what you mean, but, when rotating objects in a given GraphicsContext at a specific point, you can use a GraphicsContainer.

I scaled everything by your scaling values and also used your hardcoded numbers...

            System.Drawing.Graphics formGraphics = this.CreateGraphics();        
            formGraphics.ScaleTransform(3f, 1);

            float width = formGraphics.MeasureString("Welcome", this.Font).Width;
            formGraphics.DrawRectangle(Pens.DarkRed, 72f, 92f, 237.25f, 151.3f);

            GraphicsContainer con = formGraphics.BeginContainer();

            Matrix mx = formGraphics.Transform; 
            mx.RotateAt(270, new PointF(72f, 92f), MatrixOrder.Append);
            mx.Translate(-83.5f, 0); 
            formGraphics.Transform = mx;
      
            string text = "Welcome";
            formGraphics.DrawString(text, this.Font, Brushes.OliveDrab, new RectangleF(83.5f, 94.99f, width, 13.44f));  

            formGraphics.EndContainer(con);

This will produce a stretched rectangle with a stretched vertical text in it

Regards,

  Thorsten.

How to perform rotation along with scaling for a text in GDI+

Hi Thorsten,

Thanks for your reply. My problem is i should not use ScaleTransform direct API. I need to do everything with my own matrix calculations. In my code, if i divide the rectangle bounds x with scaling factor x means, it rendered accurately. but i need to change the matrix.translate() co ordinates values. Thanks for your help.

Regards,

Pradeep L

How to perform rotation along with scaling for a text in GDI+

Hi Thorsten,

Thanks for your reply. My problem is i should not use ScaleTransform direct API. I need to do everything with my own matrix calculations.

... so I think the best would be to do some LinearAlgebra on a sheet of paper, to keep track of all the points you are interested in.

(In fact, I still havent got, what exactly you want to achieve...)

Regards,

  Thorsten

3 Layer architecture with program and website

Hello I hope someone can help me. I'm creating a solution wich holds a program and a website in a 3 layer architecture. Whilst trying to access the data from the database things get dodgy. I'll try to explain my problem.

I use the following projects: 

1. InternalProgram: the application

2. Website: the website ^^

3. BlCommon: wich holds the business logic common to both the site and the internal program

4. DAL: the data acces layer wich holds the database and classes to acces the information wich it holds.

5. Runner: A project to "translate" the dataobjects from the business logic and the DAL database layer. Simply to avoidi circular dependancy

I can show the products from my database in a form inside my internalprogram layer with no issues. The chain I use is the same when I try to acces the same product data in the website layer. However the website layer returns the following error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: An attempt to attach an auto-named database for file C:\<myPathToDatabase>\Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

My connection string is relative: 

Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True

My code requests a list of products:

public static List<ProductDO> GetAllProducts()
        {
            using (SqlConnection connection = getConnection())
            {
                using (SqlCommand command = new SqlCommand("select id, afbeelding, naam, omschrijving, prijs from Producten", connection))
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        List<ProductDO> productsDO = new List<ProductDO>();
                        while (reader.Read())
                        {
                            ProductDO productDO = new ProductDO(
                                                        Convert.ToInt32(reader["id"]),
                                                        reader["afbeelding"].ToString(),
                                                        reader["naam"].ToString(),
                                                        reader["omschrijving"].ToString(),
                                                        Convert.ToDouble(reader["prijs"]));
                            productsDO.Add(productDO);
                        }                        
                        return productsDO;
                    }
                }
            }
        }

That list is sent to the the businessLayer wich converts it to a list of products after converting it from productDO

The code to convert from productDO to product:

public static Product convertFromDo(ProductDO productDO) 
        {
            Product product = new Product(productDO.Id, productDO.AfbeeldingsLocatie, productDO.Naam, productDO.Omschrijving, productDO.Prijs);
            return product;
        }

the code to get the list of products

public static List<Product> GetAllProducts() 
        {
            List<Product> allProducts = new List<Product>();
            
            List<ProductDO> allProductsDO = DataAccess.GetAllProducts();

            foreach (ProductDO pdo in allProductsDO) 
            {
                allProducts.Add(convertFromDo(pdo));
            }

            return allProducts;
        }

the code to display the list of products in my winform: this code works fine

List<Product> allProducts = Product.GetAllProducts();
            foreach (Product p in allProducts)
            {
                labelAllProducts.Text += p.Naam + Environment.NewLine;
                
            }

however when i do the same thing in my website layer:

List<Product> allProducts = Product.GetAllProducts();
        foreach (Product p in allProducts)
        {
            labelAllProducts.Text += p.Naam + "<br />";
        }

it crashes on the dataacces layer line: connection.open();

Can someone plz help me out?

Thx

3 Layer architecture with program and website

It sounds to me like your internal program has already attached the database, and your website is trying to do the same.  Have you thought about just attaching the database and changing the connection string to use that database on both the internal application and website?  Essentially, the way you have it set up is you can use one or the other, but not both at the same time.

3 Layer architecture with program and website

Regarding the first error where is your db residing? can you use the full path to it instead and try, example:

Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\User\MyApp\Database.mdf;Integrated Security=True

You say its crashing on connection.Open() what is the error you getting?


Fouad Roumieh

3 Layer architecture with program and website

You say its crashing on connection.Open() what is the error you getting?


Fouad Roumieh

He posted the exception above:

System.Data.SqlClient.SqlException
An attempt to attach an auto-named database for file C:\<myPathToDatabase>\Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Mark as answer or vote as helpful if you find it useful | Igor

3 Layer architecture with program and website

I already commented on the exception sent, but its not clear if its two issues or one.

Fouad Roumieh

3 Layer architecture with program and website

I indeed need to be able to acces the database from both the internal application as from the website project. I suspect as you suggest that the problem resides in the connection string.

The website has products wich can only be managed with the internal application.

How can i change the connection string so both projects can acces the database at the same time?

3 Layer architecture with program and website

I only get that error from the website not from the internal program. The program runs fine, the absolute path to the database is: C:\Users\Yves\Desktop\Eindwerk Syntra\Eindwerk\DAL\Database.mdf 

However I need that path to be relative so I can deploy the project on other computers.

3 Layer architecture with program and website

It's just the one issue, on the website. The internal program runs fine

3 Layer architecture with program and website

I recommend you install Sql Service and attach the database to the sql server and access it that way. That would solve all your problems immediately.

If that is no option and all of your code is running in the same process then you should setup some type of sharing mechanism using locks because the file can only be open by one thread or process at a time. Here is a rough example:

using System.Threading;
using System.Data.SqlClient;
using System;

public class DatabaseHelper : IDisposable
{
   private static object lockObj = new Object();

   public SqlConnection GetConnection()
   {
      Monitor.Enter(lockObj); // this will block until it aquires a lock. There are plenty of overloads for this method
      return new SqlConnection("yourConnectionString or app.config/web.config connection string name");
   }

   public void Dispose()
   {
      Monitor.Exit(lockObj);
   }
}


public class someClientclass
{
   public void SomeMethod()
   {
      var dbHelper = new DatabaseHelper();
      var connection = dbHelper.GetConnection();
      try{
         // do stuff with your connection
      }
      finally{
         connection.Dispose(); // order is important here
         dbHelper.Dispose();
      }
   }
}


Mark as answer or vote as helpful if you find it useful | Igor

3 Layer architecture with program and website

Even if I comment out all the code that accesses the db from the internal program and just keep the website code. The error still remains. So no multiple processes are trying to acces the database.

3 Layer architecture with program and website

I hope I understand your problem correctly in that you are still getting that exception on your web site. If not please correct me.

A web site is multi-threaded by default so that multiple requests can be served independent of each other. This means that 2 incoming requests could potentially access your database at the same point in time. As long as your web site is on one server (not a multi-server setup, ie webfarm of some type) then you could use Monitor.Enter/Exit to syncronize access to the database. Again, this is not ideal. What you should really do is attach this database to a Sql Server instance which has no problems serving simultaneous requests.


Mark as answer or vote as helpful if you find it useful | Igor

3 Layer architecture with program and website

So did you try it with the full path and it didn't work? just for testing purposes. Also try adding the UserInstance=true to your connection string as below:

Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;


Fouad Roumieh


Error "Incorrect syntax near the keyword 'Select'."

Hi All, I am getting error "Incorrect syntax near the keyword 'Select'." while running the below query. Please let me know how to fix it.

DECLARE @DATEPROCESS DATETIME;
SET @DATEPROCESS = CAST(DATEADD(D, -((DATEPART(WEEKDAY, GETDATE()) + 1 + @@DATEFIRST) % 7), GETDATE()) AS DATE)
insert into tempjoin([PART], [SPLRNAME], [SHIPDAYS], [SPRICE]) values
(Select distinct
RC. CAT_PART AS PART, 
RC. CAT_SUPPLIER AS SUPPLIER, 
FFC.[Ships Within Days] AS SHIPDAYS,
ffc.[Sell Price] AS SPRICE
from fri_full_Catalog FFC
INNER JOIN
R5PARTS RP ON (RP.PAR_UDFCHAR06 = FFC.[DSSI ITEM #] AND RP.PAR_ORG='USA' AND FFC.fri_Org='USA' and 
FRI_CREATED=@DATEPROCESS)
INNER JOIN
R5CATALOGUE RC ON RP.PAR_CODE=RC.CAT_PART AND RC.CAT_PART_ORG='USA'
AND (RC.CAT_SUPPLIER=REPLACE(REPLACE([SPLR NAME],'&','-'), '''', '') and 
((FFC.[Ships Within Days] <>  RC.CAT_LEADTIME)  OR (FFC.[Sell Price]<> RC.CAT_GROSS))))


Error "Incorrect syntax near the keyword 'Select'."

I'm seeing spaces between the . and column name in below, clear that:

Select distinct
RC.<space>CAT_PART AS PART, 
RC.<space>CAT_SUPPLIER AS SUPPLIER, 


Fouad Roumieh

How to perform rotation along with scaling for a text in GDI+

Hi ,

Thanks for your suggestion. Now i can get the rotation matrix by manually and perform translation. But still my confusion in setting translation points alone.

Please find the code snippet below:

void ScaleAndRotate()

 {

            System.Drawing.Graphics formGraphics = this.CreateGraphics(); 

           float width = formGraphics.MeasureString("Welcome", this.Font).Width;
            formGraphics.DrawRectangle(new Pen(myBrush), 72f, 92f, 237.25f, 151.3f);
            Matrix rotationMatrix = GetRotatingMatrix(270);
            formGraphics.ScaleTransform(3f, 1);
            rotationMatrix.Scale(3f, 1);
            rotationMatrix.Translate(-17.4f, 324f, MatrixOrder.Append);
            string text = "Welcome";
            formGraphics.Transform = rotationMatrix;
            formGraphics.DrawString(text, this.Font, myBrush, new RectangleF(83.5f, 94.99f, width,    13.44f));

}

In this code i have drawn one rectangle and get rotation matrix. If i reduce the drawstring method, rectangleF.X value as rectangleF.X /scaling value, its working good. But i dont want to reduce the rectangleF.X value.instead of that i need to  construct exact transform matrix by performing matrix.translate method. Can you please help me?

Win10/ VS2015 win store app question

Hi,

Does anyone know about how Bluetooth will work in win store apps in the next win 10/visual studio 2015?  Currently there are methods available for win phones that are not available for RT.  Will the next versions roll these into 1 in that anything that works on phone will work on RT...is that the overall plan? 

We are having issues with some Bluetooth connections in an RT app that don't seem to be present on the phone and I am just wondering if the next update might fix this for me.

Thanks

Win10/ VS2015 win store app question

Hello Ireland75

We have posted samples of how Windows Universal Applications works in the new platform. There is one that probably will be of your interest, this one show how Bluetooth works, you can find it here:

Bluetoothadvertisement

You can learn more about Universal Windows Platform (UWP) from here:

Guide to Universal Windows Platform (UWP) apps

Hope this helps.



Friday, April 24, 2015

Windows 10 Universal App ( UAP) Styles

As Raiford says, the Windows Universal Platform provides much more flexibility for responsive design than Universal Windows 8.1 does. Converged controls, API contracts, and new Xaml features such as adaptive triggers and RelativePanel make it much easier for a single Xaml file to target multiple device types in many cases. In others you'll still want to provide separate Xaml files for different devices.

Depending on your app's specific needs you may use different styles for different device sizes and capabilities even within the same executable.

For more details check out Build next week!